使用c#统一NullReferenceException错误

时间:2016-03-19 15:19:27

标签: c# unity3d nullreferenceexception

我试图使用团结制作游戏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)

我确认所有在统一中的引用都是正确的,Score保留在0并且对象不会破坏但是在添加它之前它们会破坏,可以帮我纠正这个错误吗?

重复通知

我已经阅读了master duplicate question的已接受答案,但它是一个非常普遍的答案(它列出了所有类型的此错误以及将要制作它们的内容但我真的不知道哪个会对我造成这个错误) ,只是因为我添加了所有相关的代码,我认为这是一个非常常见的错误,其他未来的用户可以从这个答案中获益,也许重新打开这个问题,有人会帮我纠正错误。

1 个答案:

答案 0 :(得分:3)

在您当前的代码中,行:

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!");
    }