Reputation: 395
I have a simple project with a button in a scene that, when tapped, starts the StartWorking function in this script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class DoWork : MonoBehaviour {
public int Cash = 5;
public void StartWorking() {
Debug.Log (Cash);
Debug.Log ("Ran!");
Cash++;
Debug.Log (Cash);
}
}
When ran and on tapping the button the console says:
0
Ran!
1
instead of expected:
5
Ran!
6
Any idea why the variable is not keeping it's set initial value in the class?
Thanks.
Upvotes: 1
Views: 8425
Reputation: 10721
When a variable is public, the value on the script does not matter. You probably have it as 0 in Inspector and this is the value used at runtime. If you want the value of the script to be used, you need to click the component setting wheel and Reset component.
If you have to see the value but want to use the script value, make it private and click the little down arrow next to the lock on top of the inspector. This will display private member as well. You won't be able to change them though via inspector, just look.
Upvotes: 6
Reputation: 3469
Cash
variable is public and I think you change the value of Cash
in inspector
.
Once you change the value of a variable in inspector, unity will ignore the initial value in code and replace it with value in inspector.
Try to change public int Cash = 5;
to private int Cash = 5;
and you will get the result you want
Upvotes: 3
Reputation: 539
Is your script linked to an object in the scene ? If it's the case, the "cash" variable can be edited in the inspector and overwrite the initialisation in your script.
Upvotes: 1