Home > OS >  Text in Canvas is not being updated correctly - Null Error
Text in Canvas is not being updated correctly - Null Error

Time:12-30

I am building out a Zelda game and I have ran into an issue -

 public void UpdateCoins()
{
   Debug.Log(GameManager.instance.currCoins);
   //coinsText.text = "Coins "   GameManager.instance.currCoins;
}

That works as expected -

But when I do this...

  public void UpdateCoins()
{
   Debug.Log(GameManager.instance.currCoins);
   coinsText.text = "Coins "   GameManager.instance.currCoins;
}

I receive an Object Reference not set to an instance of the object error.

enter image description here

As you can see it is set. Here is my simple GameManager script

public static GameManager instance;

public int currCoins;

private void Awake()
{
    instance = this;
}
// Start is called before the first frame update
void Start()
{
    
}

// Update is called once per frame
void Update()
{
    
}


public void GetCoins(int coinsToAdd)
{
    currCoins  = coinsToAdd;

    UIManager.instance.UpdateCoins();
}
}

Any thoughts on why this isn't working the way it should?

Thanks!

CodePudding user response:

Try add more logs Either the coinsText or the coinsText.text is null, so what I would do is:

Debug.Log(coinsText);
if(coinsText != null) Debug.Log(coinsText.text);

CodePudding user response:

I'm sure you'll make a great Zelda game but let's fix your issue here first , you are trying to access to an int GameManager.instance.currCoins but returns null simply because the currCoins you're using is not even to been set to zero. Also as a tip if you are going to use an int in a string text or something always use ToString() : coinsText.text = "Coins " GameManager.instance.currCoins.ToString(); Number 2 issue here , your use of singleton it should be like this

public static GameManager instance;

public void Awake()
{
    if(instance == null){
        instace = this;
    }else
    {
        DontDestroyOnLoad(gameObject);
    }
}

Last issue that may not be one now but in the future change the name of this method now while you still can public void GetCoins(int coinsToAdd)to something like AddCoins(int coinsToAdd)

  • Related