我的腳本...爲什麼我一直得到這個NullReferenceException錯誤?
using UnityEngine;
using System.Collections;
public class CountDownTimer : MonoBehaviour {
public int score;
float timeRemaining = 15;
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
timeRemaining -= Time.deltaTime;
score = GetComponent<TriggerZone>().score;
}
void OnGUI(){
if (timeRemaining > 0) {
GUI.Label(new Rect(100, 100, 200, 100), "Time Remaining: "+(int)timeRemaining);
}
else{
GUI.Label(new Rect(100, 100, 200, 100), "Times up your score was: " + score + ". Press the r button to restart, or ESC to quit.");
if (Input.GetKeyDown("r"))
Application.LoadLevel("Testing Grounds");
if (Input.GetKey("escape"))
Application.Quit();
}
}
}
錯誤:
NullReferenceException: Object reference not set to an instance of an object CountDownTimer.Update() (at Assets/Scripts/CountDownTimer.cs:16)
我想不出什麼可能會造成這個錯誤。據我瞭解,這是試圖告訴我,一些東西不存在,但我想不出可能是什麼。 「score = GetComponent()。score;」正在訪問包含分數值的另一個腳本,以便當計時器用完時它會告知玩家他們的分數,並讓他們選擇退出或重新開始遊戲。
此外,如果它幫助這裏是其它腳本...
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
公共類TriggerZone:MonoBehaviour {
public Text MyText;
public int score;
// Use this for initialization
void Start() {
MyText.text = "";
}
// Update is called once per frame
void Update() {
MyText.text = "$" + score;
}
void OnTriggerEnter(Collider coll) {
if (coll.gameObject.HasTag ("ValueLevel1"))
score = score + 5;
if (coll.gameObject.HasTag ("ValueLevel2"))
score = score + 25;
if (coll.gameObject.HasTag ("ValueLevel3"))
score = score + 50;
if (coll.gameObject.HasTag ("ValueLevel4"))
score = score + 100;
if (coll.CompareTag ("Pickable")) {
coll.gameObject.SetActive(false);
}
}
}
這聽起來像'GetComponent()'是'返回null',而是因爲你沒有足夠的發佈代碼爲我們重現您的問題,我們不能肯定。 –
Enigmativity
你還需要什麼?另一個腳本? – Sie