我的脚本...为什么我一直得到这个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