【发布时间】:2017-02-10 12:51:27
【问题描述】:
该项目运行良好,直到达到某个点,然后突然开始抛出 NRE。 这是一些源代码:
void Start(){
myhealth = GetComponentInChildren<HealthBar>();
if(myhealth == null)
{
Debug.Log("myhealth is null !!"); //It never outputs something here
}
}
//And Here it works :
public void ApplyDamage(float amount)
{
myhealth.DamageEnemy(amount);
if (GetHealth() <= 0)
{
[...]
}
}
//Then suddenly it throws NRE's here when accesing it from another Script :
public void AddHealth(float a)
{
myhealth.HealEnemy(a); //Here
}
public float GetHealth()
{
return myhealth.GetHealth(); //And here
}
在 HealthBar 脚本中有这些变量和这些函数:
public float maxHealth;
public float currentHealth;
private float originalScale;
public void DamageEnemy(float giveDamage)
{
currentHealth -= giveDamage;
}
public void HealEnemy(float heal)
{
currentHealth += heal;
}
public float GetHealth()
{
return currentHealth;
}
脚本似乎没有理由抛出 NRE,但它仍然存在。
【问题讨论】:
-
第一个块中的所有代码是否都在同一个脚本上?
-
是的。第二块是另一个脚本
-
你在哪里声明变量myhealth?当您收到 NRE 时,您是否使用相同的头等舱实例?您上面的代码错过了一些上下文。特别是调用 Start、ApplyDamage 和 AddHealth 的代码
-
一个 Unity 脚本 (MonoDevelop) 在对象开始进入游戏时立即调用 Start() 函数 -> myhealth 变量从 Start() 开始始终是相同的,并且永远不会改变
-
发布您的
HealthBar脚本
标签: c# unity3d nullreferenceexception unity5