簡體   English   中英

計分器不適用於Unity3D

[英]Score counter not working on Unity3D

因此,我正在編寫一個足球橫桿挑戰游戲(這是我有史以來的第一款游戲),並且我向橫桿添加了一個腳本,如下所示:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class crossbarscript : MonoBehaviour {
public AudioSource ping;
public static int score;
public Rigidbody rb;
public Text text;

// Use this for initialization
void Start () {
    ping = GetComponent<AudioSource>();

    rb = GetComponent<Rigidbody>();
    score  = 0;


}

// Update is called once per frame
public void OnCollisionEnter (Collision col) {

    if(col.gameObject.name == "Ball")
    {

        text = GetComponent<Text>();
        text.text = "Score: " + score; //This is the line the error is pointing at

        ping.Play();
        rb.freezeRotation = true;
    }



}
}

在控制台中,我得到以下信息:NullreferenceException:對象引用未設置為對象的實例

我要嘗試做的是使它每次擊中橫桿(腳本附加到的對象)時,將其添加到左上角文本的得分上。 請讓我知道是否有辦法解決此問題,或者是否應該以其他方式解決此問題,謝謝。

text = GetComponent<Text>();

是不必要的,並且會引起您的問題。 您正在運行此腳本的GameObject不包含Text組件,並且正在重新運行null,這會導致text.text在下一行失敗。

您不需要在沖突代碼中調用GetComponent<Text>() 您已經有了一個公共變量,應該在設計器中通過將Text對象拖到腳本上來設置它。 設置完畢后,您無需在代碼中進行設置。

請參見“滾動球”教程“ 3.3:顯示分數和文本 ”,以獲取有關如何在代碼中使用Text顯示分數的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM