- Home /
why does return values method runs multiple times when it is called only once?
Hello. i just want to understand how the code below run. i cant figure out why the return value method called multiple times on runtime or exit runtime.
i am using visual studio to edit script
code is written in c#
using unity for my game developement
this is my example
public static class R1
{
public static int N1;
public static int GetN1()
{
Debug.Log("GetN1");
Debug.Log(N1);
N1++;
Debug.Log(N1);
Return N1;
}
}
public class Tester : Monobehaviour
{
private int A = R1.GetN1();
private void Awake()
{
Debug.Log("Awake");
Debug.Log(A);
}
private void Start()
{
Debug.Log("Start");
Debug.Log(A);
}
private void OnEnable()
{
Debug.Log("Enable");
Debug.Log(A);
}
private void OnDisable()
{
Debug.Log("Disable");
Debug.Log(A);
}
}
when i run the code the outputs are
GetN1
0
1
GetN1
1
2
Awake
2
Enable
2
//when i disable the game object (from unity inspector)
Disable
2
//when i enable the game object
Enable
2
//same goes when i disable or enable the script (Tester)
//but when i exit unity player(means stop running the code in unity)
//the output is
Disable
2
GetN1
2
3
from what i understand i only called GetN1 method once, but from the output it seems to be called when i start runtime and when i exit runtime.
hope someone can enlighten me.
thank you in advance:)
Answer by Bunny83 · May 04, 2020 at 01:06 AM
You call your GetN1 method from a field initializer:
private int A = R1.GetN1();
Field initializers are executed even before the constructor of an object is executed. This happens whenever the object is created. When you enter or leave playmode the whole managed environment is serialized, destroyed, reloaded and deserialized. The objects do exist during edit time just as they exist during runtime. However when you switch between edit and play mode all objects are actually recreated.
For MonoBehaviours you should generally avoid executing code from the constructor or field initializer. That's because the object creation of components is actually done on a seperate thread (loading thread). Since most of the Unity API is not thread safe you can easily run into problems.
However for your specific case I don't really see any issues. Creating a unique ID for a session should work just fine that way. Keep in mind that when testing in the editor your scene might get saved / reloaded even several times. The additional calls you see when you exit playmode is most likely due to the reloading of the serialized scene that is currently loaded inside the editor.
"When you enter or leave playmode the whole managed environment is serialized, destroyed, reloaded and deserialized."
thanks for the clarification and the advice:)
this generally did not really cause any problems but its good to know.