0

I declared a variable in a script:

private int count;

Init it at Awake() method:

void Awake() 
{
    count = 1;
}

Keep checking an print the value of it:

void Update ()
{
    Debug.Log(count);
}

Then declared a method to change the value of this variable:

public void ChangeValue()
{
    count = 2;
    Debug.Log("button has being pressed!");
    Debug.Log(count);
}

Then create a button to call this method to change the value, the value that print out in update() method does not change without any error.

Here is the log:

Picture of Unity console, showing debug output

No matter how many times I pressed the button, the count variable in Update() method is still "1".

How can I update the variable value inside the Update() method?

2 Answers 2

2

Your script is either attached to the-same GameObject twice or attached to multiple GameObjects. The images below shows how to easily find out and fix it for each scenario.

Your script is attached to the-same GameObject more than once:

enter image description here

Your script is attached to multiple GameObjects:

enter image description here


That should solve your problem. If not then it's a comibation of this and Collapse is enabled. So you must also disable Collapse too as Ariss mentioned.

enter image description here

Sign up to request clarification or add additional context in comments.

6 Comments

Did you really intend to embed that same gif twice?
Nope. It was a typo in the first link.
Problom SOLVED! Thank you so much! I attached the script to multiple GameObjects by misstake. @Programmer
Nice. Don't forget to accept my answer to mark it as solved.
is it just pitching on the tick on the left side of you answer?@Programmer
|
1

You have your log set to collapse, which groups together the same items being logged, it looks like you already are achieving the affect you wanted where it is printing 2.

4 Comments

This is at least plausible, given the nature of the collapsed logs.
but the upate() still keep print count value as "1" times and times again, it still using the "old" value.
can you upload your full script to hastebin.com @waynelee, it provide more information
Not just in the log, when I do some conditional judgment base on the count value in update() method, It's still the wrong value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.