【发布时间】:2014-10-11 12:02:00
【问题描述】:
如何更改另一个类中的变量?
public class Manager : MonoBehaviour {
public bool isDead = false;
void Start () {
GameObject Slugbert = (GameObject)Instantiate(Resources.Load("Slugbert"));
}
void Update () {
}
}
我正在尝试将 isDead 布尔值从 false 更改为 true。
using UnityEngine;
using System.Collections;
using System;
public class Health : MonoBehaviour {
public GameObject obj;
Manager manager;
public int maxHealth = 10;
public int health = 10;
public GameObject deathInstance = null;
public Vector2 deathInstanceOffset = new Vector2(0,0);
void Start () {
manager = obj.GetComponent<Manager>();
health = maxHealth;
}
void Update () {
if (Input.GetKey ("up")) {
Debug.Log ("Self Destruct Activated");
TakeDamage();
}
}
public void TakeDamage()
{
health -= 100;
if (health <= 0)
{
OnKill();
Debug.Log ("Running it");
}
}
public void OnKill()
{
manager.isDead = true;
Debug.Log(manager.isDead);
if (deathInstance) {
var pos = gameObject.transform.position;
GameObject deathObject = Instantiate (deathInstance, new Vector3(pos.x + deathInstanceOffset.x, pos.y + deathInstanceOffset.y, pos.z), Quaternion.identity) as GameObject;
}
Destroy(gameObject);
}
}
我在 debug.log 中添加了显示 manager.isDead 的值,并且打印为 true,但是在检查器中,当我运行它并单击 GameControl 时,包含 Manager.cs 的对象显示 isDead = false .我不确定如何让 GameControl Manager.cs 中 isDead 的值等于 true。
谢谢,我是 Unity 的新手
【问题讨论】:
-
@O.R.Mapper 并非每个
NullReferenceException都有相同的场景。 -
@Shaharyar:当
manager.isDead = true;线上有NullReferenceException时,只有一种可能的情况,即manager是null。 OP 似乎没有得出这个结论,所以他们的问题完全归结为我链接的问题 - “这是什么意思,我能做些什么?” -
@O.R.Mapper 我的意思是我们应该指出导致异常的实际问题。