使用c#统一时出现NullReferenceException错误

NullReferenceException error in unity using c#

我正在尝试使用 unity 5 制作游戏,但我在这个关卡中遇到了问题 GameController.cs:

public class GameController : MonoBehaviour
{

    private int score;

    void Start()
    {
        score = 0;
        UpdateScore();
    }

    public void AddScore(int newScore)
    {
        score += newScore;
        UpdateScore();
    }

    void UpdateScore()
    {
        scoreText.text = "Score : " + score.ToString();
    }

这不是完整的代码,这是代码的唯一相关部分,而且 DestroyByContact.cs:

public class DestroyByContact : MonoBehaviour 
{
    private GameController gameController;

    public int scoreValue;


    void Start()
    {
        GameObject gameControllerObject = GameObject.FindGameObjectWithTag("GameController");
        if (gameController != null)
        {
            gameController = gameControllerObject.GetComponent<GameController>();
        }
        if (gameController == null)
        {
            Debug.Log("Cannot find 'GameController' script!");
        }
    }

    void OnTriggerEnter(Collider other)
    {
        Debug.Log(scoreValue);    
        gameController.AddScore(scoreValue);  # This is line 38
        Destroy(other.gameObject);
        Destroy(this.gameObject);
    }
}

这是我从 Unity 控制台得到的完整错误:

NullReferenceException: Object reference not set to an instance of an object
DestroyByContact.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Assets/Scripts/DestroyByContact.cs:38)

我 assgin 统一正确的所有引用,Score 保持在 0 并且对象不会销毁但是在添加之前它们会销毁,请帮我纠正这个错误吗?

重复通知

我阅读了 master duplicate question 的公认答案,但这是一个非常笼统的答案(它列出了所有类型的错误以及导致错误的原因,但我真的不知道是哪个错误对我造成的),仅仅因为我添加了所有相关代码,我认为这是一个非常常见的错误,其他未来的用户将从这个答案中受益,也许重新打开问题,有人会帮助我纠正错误。

在您当前的代码中,行:

gameController = gameControllerObject.GetComponent<GameController>();

永远不会执行,因为您在实际分配之前检查 gameController 是否不为空。

我认为你的错误在于第一个 if (gameController != null)。 您应该检查 gameControllerObject 是否不为 null,如下所示:

GameObject gameControllerObject = GameObject.FindGameObjectWithTag("GameController");
    if (gameControllerObject != null) //Replace gameController with gameControllerObject 
    {
        gameController = gameControllerObject.GetComponent<GameController>();
    }
    if (gameController == null)
    {
        Debug.Log("Cannot find 'GameController' script!");
    }