Unity Script (c#)中的奇怪NullReferenceException

本文关键字:NullReferenceException Script Unity | 更新日期: 2023-09-27 18:09:49

项目工作正常,直到达到某一点,然后突然开始抛出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's,但它仍然这样做。

Unity Script (c#)中的奇怪NullReferenceException

就像您在Start()函数中所做的那样,尝试添加

if(myhealth == null)
{
    Debug.Log("myhealth is null !!");
}

public void AddHealth(float a)
{
    myhealth.HealEnemy(a);
}

指向

public void AddHealth(float a)
{
    if(myhealth == null)
    {
        Debug.Log("myhealth is null !!");
    }
    else
        myhealth.HealEnemy(a);
}

myhealth = GetComponentInChildren<HealthBar>();Start()中得到myhealth,这本身就很好。

但是当获得该组件的子对象被销毁、删除或停用时会发生什么?您可能已经猜到了,该组件也不再存在了。