为什么我在尝试在Unity C#中创建HealthPack时遇到NullReferenceException?
问题描述:
好吧,我和gals我有一个问题再次与一些代码。基本上,一旦我开始并试图建立一个健康包它抛出一个错误:为什么我在尝试在Unity C#中创建HealthPack时遇到NullReferenceException?
的NullReferenceException:)未将对象引用设置到对象 HealthSpawnerScript.Update(实例(在资产/脚本/ HealthSpawnerScript.cs: 31)
下面是我正在运行的代码。 GameObject PlayerController包含一个用于返回PlayerHealth()的播放器健康的方法。在唤醒时,我设置了playerController来查找我之后的脚本和方法。然后在更新中,我试图调用该方法并将其分配给稍后在脚本中使用的变量。我知道这应该很简单,但我有一个大脑放屁球员。
public PlayerController playerController;
private int healthHolder;
void OnAwake()
{
playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController>();
}
// Use this for initialization
void Start()
{
//set healthExist to false to indicate no health packs exist on game start
healthExist = false;
//playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController>();
}
// Update is called once per frame
void Update()
{
healthHolder = playerController.PlayerHealth();
答
没有Unity回拨函数OnAwake
。您可能正在寻找Awake
函数。
如果这是固定的,并且您的问题仍然存在,您必须将代码分成几块,找出发生了什么故障。
playerController = GameObject.Find ("PlayerHealth").GetComponent<PlayerController>();
应改为
void Awake()
{
GameObject obj = GameObject.Find("PlayerHealth");
if (obj == null)
{
Debug.Log("Failed to find PlayerHealth GameObject");
return;
}
playerController = obj.GetComponent<PlayerController>();
if (playerController == null)
{
Debug.Log("No PlayerController script is attached to obj");
}
}
所以,如果GameObject.Find("PlayerHealth")
失败,这意味着有一个在现场看到,名称的游戏对象。请检查拼写。
如果obj.GetComponent<PlayerController>();
失败,则不会有附加到PlayerHealth
GameObject的脚本PlayerController
。简化你的问题!
不是我需要的东西,但我想通了,我调用PlayerController方法PlayerHealth附加到PlayerController而不是定位实际的对象将是PlayerShip的脚本PlayerController对它。 – Phillipv20
好的。 “OnAwake”函数怎么样?那是正确的? – Programmer