Search code examples
c#unity-game-enginevariablestext

Unity2D error spam when setting a text object tot a variable


I am setting a text object to a variable called dashCooldownCounter. Everything works properly but it gives me thousands of error messages that is filling up my console and makes it impossible to see any important error messages. Here is the code, I didn't include lots of non-important code so you should just know that the dashCooldownCounter is working even though you won't see it

public Text time;

void update()
{
    time.text = (Mathf.Round(dashCooldownCounter * 10) / 10).ToString();
}

the error says:

NullReferenceException: Object reference not set to an instance of an object
PlayerMovement.Update () (at Assets/Scripts/PlayerMovement.cs:62)

Line 62 is the time.text line. I get what it thinks is happening and why its yelling at me but i don't know how to stop it from doing it.

I have tried many things to try and fix it. Just please help.


Solution

  • The only NullReferenceException possible in your Update method is time.text, where you are trying to access the text property in time, but time is null. The only possible explanation for that is that time is not assigned in the inspector. Make sure it's not set to None.

    Side notes:

    1. I'm guessing you just rewrote the line, but just to make sure, Update as an uppercase.
    2. You said [...] error messages that is filling up my console and makes it impossible to see any important error messages. That is because a NullReferenceException is an extremely important error message, one that would easily break your application in build. If it doesn't crash your app, your app may start to act weirdly, your component holding the error might stop working etc. A NullReferenceException should be the first thing you fix before you investigate any other bugs you may have, because fixing it might just solves everything.