Scripts/buttons getting old (prefab?) values of variables

Basic Problem:
The scripts in my game are convinced that certain variables are set to certain values even though I can see in the Inspector and in the Game and Scene Views that the associated objects do not have those variable values. This has happened with ints, with Lists, with TMP texts, and so on.

In each case, the problem seems to be that while the correct values are showing up in the Game/Scene Views and in the Inspector, the scripts meant to be evaluating those values only ever get the “old”/“default”/“prefab” values of those variable. Any help would be greatly appreciated!

Details You Can Skip:
To make up an example: an int might start at 0, and get gradually incremented as the game progresses. That int might be converted .ToString() and passed to a TextMesh Pro object for display. The TMP object might show the numbers increasing from 0 to 10 when you run the game. And the player might press a button when they see the number reach “10.”

The problem in this hypothetical scenario is that the script triggered by that button always only thinks the value of the int variable is 0 (the value it started with/its value in the prefab), and that the value of the TMP string is “0”. So, if the script compares the variable with the value it ought to be (in order to solve some puzzle, say), it always reports the wrong result.

This is often, though not always, associated with scripts triggered by buttons. This is often, though not always, associated with objects Instantiate()ed from prefabs. And I have often been able to “solve” the problem by declaring the variables in question “static.”

(For example, if I declare the hypothetical int above “private static int,” suddenly the button’s script reports the updated values for the int. And if I make the TMP text object static, the button’s script reports the updated values for the string version of the int.)

Summary I need the values reported/found/returned/accessed by the scripts to be the values shown in the game and in the Inspector. Declaring them all “static” often works, but also seems to be a kludge. There is clearly some important conceptual thing I am not understanding about how Unity and/or C# handles objects, variables, prefabs, or something. Any enlightenment you can offer would be appreciated!

It sounds like you may be reading data from a different instance than the one you are writing to. This is why a static variable would give you the correct value. Set breakpoints in your IDE and inspect the instance ID or use Debug.Log(GetInstanceID()) in the get and set functions to confirm. How are you Instantiating and referencing the prefab?

Thanks @nowayout2k! Typically I declare a new variable and set it equal to Instantiate(prefab). This is sometimes done inside a for() loop when I need multiple instances of the same prefab.

The instance ID idea is new to me, so I suspect it shall be helpful. Will report back.

Thanks again!