Variable value doesn't change

Hello everyone,

Ths has been driving me crazy for a good few hours now and after looking up and down Google I’m no closer to finding the answer to this.

I’ve got this very basic script:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PlayerDetails : MonoBehaviour {
    private int i;
       
    void Awake()
    {
        i = 0;
       
    }
    public void ChangeMe()
    {
        i = 2;
    }

   void Update()
    {
        Debug.Logg(i);
        if (i == 2)
        {
            Debug.Log(i);
          }
    }

}

Very simple script as I said. Now, this may be me being daft, but the way I read this is:

  • i is delcared (private int i)
  • i is initialised (in Awake)
  • ChangeMe is called from the OnClick() of a button in the scene which should change i value to 2
  • Update constantly shows the value of I
    ** 0 by default
    ** 2 if the value is 2

What happens in my program (new scene, new project, no other scripts but this) is:

0 is showed every frame. When the button is pressed 2 is shown ONCE, then it goes back to 0.

This is where I’m confused. Shouldn’t i stay 2 after the function changes it? If not, how to I make it stay 2 in this context please?

Many thanks for your time!!

Alex

Did you manage to fix this? I am having the exact same problem right now and its so weird, I feel like I am making a noob mistake

There’s nothing wrong with your code other than having an extra ‘g’ on line 21. What unity does with messages printed to the console is that it collapses them by default. It checks the value of the output and marks a quantity for times that output has been seen. It won’t print line by line unless you uncheck Collapse in the Console. You don’t want to use the console to display things like this on Update() either. Best is to mark the field with [SerializeField] and just inspect the object the script is on. You’ll see the value without getting spammed by Console entries. The less you use Update() the better. You can remove the [SerializeField] attribute later if you don’t need to modify the value at design time.

using UnityEngine;
 
public class PlayerDetails : MonoBehaviour {
    [SerializeField] private int i;
        
    void Awake() {
        i = 0;
    }
    
    public void ChangeMe()
    {
        i = 2;
    }
}