【发布时间】:2016-03-02 16:22:56
【问题描述】:
我正在尝试为我的游戏添加评分系统。但是,每当我玩游戏时都会出现此错误,并且当小行星与玩家或子弹相撞时,它们不会再摧毁。
我的错误信息是这样的: NullReferenceException:对象引用未设置为对象的实例 DestroyByContact.OnTriggerEnter2D(UnityEngine.Collider2D 其他)(在 Assets/Scripts/DestroyByContact.cs:47)
我应该注意到,所有游戏对象上也都有正确的标签。
还有一些代码:
using UnityEngine;
using System.Collections;
public class DestroyByContact : MonoBehaviour {
public GameObject explosion;
public GameObject playerExplosion;
public int scoreValue;
private GameController gameController;
void start () {
GameObject gameControllerObject = GameObject.FindWithTag ("GameController");
if (gameControllerObject != null) {
gameController = gameControllerObject.GetComponent <GameController> ();
}
if (gameController == null)
{
Debug.Log ("Cannot find 'GameController' script");
}
}
void OnTriggerEnter2D(Collider2D other){
if (other.tag == "Boundary") {
return;
}
Instantiate(explosion, transform.position, transform.rotation);
if (other.tag == "Player") {
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
}
gameController.AddScore (scoreValue);
Destroy(other.gameObject);
Destroy(gameObject);
}
}
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameController : MonoBehaviour {
public GameObject[] asteroids;
public Vector3 spawnValues;
public int asteroidCount;
public float spawnWait;
public float startWait;
public float waveWait;
public GUIText scoreText;
private int score;
void Start () {
score = 0;
UpdateScore ();
StartCoroutine (spawnWaves ());
}
IEnumerator spawnWaves () {
yield return new WaitForSeconds (startWait);
while (asteroidCount > 0) {
for (int i = 0; i < asteroidCount; i++) {
GameObject asteroid = asteroids[Random.Range(0, asteroids.Length)];
Vector3 spawnPosition = new Vector3 (spawnValues.x, Random.Range (-spawnValues.y, spawnValues.y), spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (asteroid, spawnPosition, spawnRotation);
yield return new WaitForSeconds (spawnWait);
}
yield return new WaitForSeconds (waveWait);
if (asteroidCount <= 95) {
asteroidCount += 5;
}
}
}
public void AddScore (int newScoreValue) {
score += newScoreValue;
UpdateScore ();
}
void UpdateScore () {
scoreText.text = "Score:" + score;
}
}
【问题讨论】:
-
DestroyByContact.cs的第 47 行是哪一行?你认为那里的变量是如何设置的?NullReferenceException通常很难调试:你做了什么来试图理解这个问题? -
第 47 行是:gameController.AddScore (scoreValue);。老实说,我对此很陌生,我正在使用一些教程来尝试和学习。我不确定如何调试它。我知道的一件事是,如果我将第 47 行放在销毁函数下方,它仍然可以工作,但不会添加分数(我想这是因为游戏对象不再在那里运行代码)。
-
标记,而不是使用 FindWithTag 从层次结构中分配 GameController。如果您不知道如何与我们分享您的 unity3d 屏幕截图,请再试一次。
标签: unity3d nullreferenceexception unity5