【发布时间】:2016-03-20 12:39:44
【问题描述】:
我正在尝试使用 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)
我将所有引用统一分配正确,Score 保持在0 并且对象不会破坏,但是在添加之前它们会破坏,请帮我纠正这个错误吗?
重复通知
我阅读了master duplicate question 的已接受答案,但这是一个非常普遍的答案(它列出了所有类型的此错误以及将导致它们的原因,但我真的不知道是哪个对我造成了此错误),只是因为我添加所有相关代码我认为这是一个非常常见的错误,其他未来的用户会从这个答案中受益,也许重新打开问题,有人会帮我纠正错误。
【问题讨论】:
-
@GrantWinney ,它说
GameController是 null ,但是为什么呢? -
@Lucas Trzesniewski ,我认为我的问题与您所说的主重复问题不太相似,肯定是同样的问题,但是重新打开它,也许有人会帮助我,谢谢!
-
@rene 感谢您向我指出这一点,我已经回复了元数据。
-
已关闭。这是一个完全相同的副本——你甚至从未学习过最基本的调试。识别什么是空是微不足道的。如果你说它不完全一样,那么请花半个小时学习如何使用调试器并自己做一些基本的标准步骤。
-
@TomTom ,我在 SO 中看到了很多 NRE 问题,但是其中很多都没有作为重复关闭,应该全部关闭吗?还是 jusr mine 和 master 问题一样?
标签: c# unity3d nullreferenceexception