简体   繁体   English

计分器不适用于Unity3D

[英]Score counter not working on Unity3D

So I'm programming a soccer crossbar challenge game (This is my first game ever) and I added a script to the crossbar that looks like this: 因此,我正在编写一个足球横杆挑战游戏(这是我有史以来的第一款游戏),并且我向横杆添加了一个脚本,如下所示:

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;
    }



}
}

And in the console, I get this: NullreferenceException: Object reference not set to an instance of an object 在控制台中,我得到以下信息:NullreferenceException:对象引用未设置为对象的实例

What I'm trying to do is make it so that every time the ball hits the crossbar (the object the script is attached to) it adds to the score on the text in the upper left corner. 我要尝试做的是使它每次击中横杆(脚本附加到的对象)时,将其添加到左上角文本的得分上。 Please let me know if there's a way to fix this or if I should do it another way, thanks. 请让我知道是否有办法解决此问题,或者是否应该以其他方式解决此问题,谢谢。

the line 线

text = GetComponent<Text>();

is unnecessary and is causing your problem. 是不必要的,并且会引起您的问题。 The GameObject you are running this script on does not contain a Text component and is retunning null, this causes text.text to fail on the next line. 您正在运行此脚本的GameObject不包含Text组件,并且正在重新运行null,这会导致text.text在下一行失败。

You should not be needing to be calling GetComponent<Text>() in your collision code. 您不需要在冲突代码中调用GetComponent<Text>() You already have a public variable, it should likely have been set in the designer by dragging the Text object on to the script. 您已经有了一个公共变量,应该在设计器中通过将Text对象拖到脚本上来设置它。 Once set there you don't need to set it in your code. 设置完毕后,您无需在代码中进行设置。

See from the Roll-A-Ball tutorial " 3.3: Displaying the Score and Text " for a example of how you should be using Text in your code to display score. 请参见“滚动球”教程“ 3.3:显示分数和文本 ”,以获取有关如何在代码中使用Text显示分数的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM