I haven’t found anything on this after an hour of searching, and I don’t remember having this problem in the past.
I got a button, and a custom function in a script that has the variable I need to change
Here’s an example of what the code looks like (just changed the names, this example has the same problem as the actual code):
public int integerNumber = 10;
public void CalledFromButton () {
integerNumber += 5;
Debug.Log(integerNumber);
}
I assign the object holding this script, to the button’s “On Click ()” function box, and select the custom function from the drop-down menu.
When I press Play and click the button, the console displays “5” (instead of 15), and increases by 5 every time I click it thereafter. The number in the console also doesn’t reset on stopping and restarting the game. Let’s say I press play and get the number to 25, then stop the game, then press Play again. When I click the button the number shown in the console is 30 (instead of 5 or 15).
I got this function working in two different ways.
I put the function in a different script, and called it using the same button.
I added a reference to the script, within the custom function and making the change (script.integetNumber += 5; ), also within the function.
Am I missing some basic function calling rules and stuff? A few hours ago I struggled with other code before realizing I had IF checks in the wrong order, so it’s not unlikely.
P.S. I’m not getting any errors or warnings in the console.
I’m referencing it also in a script for the UI to show the number on-screen. And I just checked, and it is 10 in the inspector (also stays at 10 even when the console number increases).
When I set it to private, it works. But I need to display it on-screen.
I thought that might be the cause! I have also scratched my head for hours in the past, only to realize that I had a magical 0 floating around that was public from testing and took me forever to figure out why my values were not correct lol
So you can then create a ‘Getter’ for this and then simply call that from your UI script
So something like this:
private int integerNumber = 10;
public void CalledFromButton()
{
integerNumber += 5;
Debug.Log("integerNumber: " + integerNumber);
}
public int GetIntegerNumber()
{
return integerNumber;
}
The way you were doing it IS possible. The problem is, the issues you were having were likely being caused by more than one instance getting called or updating one instance and reading out another, or something strange like that. So the best way is to work mainly with Getters and Setters when handling data and values and such.
I just noticed the other part about the 10 changing in console but not on your output. That is because your output needs to call the getter each time the button is pressed. I’m assuming then you only have it hooked up via Start() you will have to put that line in the UI’s Update() method. there are better ways to handle this, but that will then have the output update.