0

i am trying to display a timer in unity. I get always this error: NullReferenceException: Object reference not set to an instance of an object. If anyone can help me it will be really nice <3

public class PlayerScore : MonoBehaviour
{
    private float timeLeft = 120f;
    public float playerScore=0;
    public GameObject timeLeftUI;
    public GameObject playerScoreUI;

    private void Start()
    {
        
        timeLeftUI.gameObject.GetComponent<Text>().text = ("Time: " + timeLeft).ToString();
    }

    // Update is called once per frame
    void Update()
    {
        timeLeft -= Time.deltaTime;
        
        
        timeLeftUI.gameObject.GetComponent<Text>().text = ("Time: " + timeLeft).ToString();
        
        //Debug.Log(timeLeft);
        if (timeLeft < 0.1) //si le time est plus petit que 0 alors la partie se termine
        {
            //partie terminé
        }
    }

    void CountScore()
    {
        playerScore = playerScore + (timeLeft * 10);
    }

}```

  • The issue is displayed in the error. It is specifying that the object does not exist. It is either the public reference of the GameObject is not assigned in the inspector, or the objects you do have assigned do not have the component Text on them. Without seeing the actual error message I can not tell you specifically which one it is. I would need to see the line that the error is thrown on to tell you that. Check your assignments and see if you are 1. assigning them and 2. assigning the correct objects in the editor. – TEEBQNE Apr 06 '21 at 19:54
  • If you're using [TextMeshPro](https://docs.unity3d.com/Manual/com.unity.textmeshpro.html) text components, you'll need to use `GetComponent` to get the text component's reference instead of Text. – ZethMatthews Apr 06 '21 at 20:08

1 Answers1

0

Try attaching the script to the GameObject in it's appropriate hierarchy, you can drag it from the asset folder in Unity directly to the GameObject.

The error NullReferenceException: Object is thrown because you are trying to use a reference and the reference is not initialized.

Adam
  • 150
  • 2
  • 12