【问题标题】:Strange NullReferenceException in Unity Script (C#)Unity Script (C#) 中的奇怪 NullReferenceException
【发布时间】: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


【解决方案1】:

就像你在 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 是使用myhealth = GetComponentInChildren&lt;HealthBar&gt;();Start() 中获得的,这本身就可以。

但是当您从中获取此组件的子对象被销毁、移除或停用时会发生什么?你可能已经猜到了,组件也不存在了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多