Search code examples
c#unityscriptunity-game-engine

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

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.


Solution

  • 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.

    You should not be needing to be calling GetComponent<Text>() in your collision code. You already have a public variable, it should likely have been set in the designer by dragging the Text object on to the script. 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.