- Home /
global variable doesn't work
Hello,
I have a problem with my global variable... In my method doSomething(), my nbwidg = 0. But, in my FixedUpdate, nbwidg = 5.
I don't understand how to get this number 5 with my doSomething methode. What is the problem, please ?
private int nbwidg;
void Start() {
OnDataReceived(...);
doSomething();
}
void OnDataReceived(Message message)
{
if ( ... )
{
nbwidg = 5;
}
}
void FixedUpdate() { ... }
void doSomething()
{
for (int i = 0; i < nbwidg; i++)
{
// I need (nbwidg = 5) here
}
}
As written, your OnDataReceived body only sets that value if a specific if
statement is satisfied. Are you sure that's satisfied?
Answer by MacDx · Dec 17, 2018 at 06:23 PM
I can think of 2 cases here that might be causing this issue.
Case #1: OnDataReceived is some kind of asynchronous method, meaning that its result can come after some time has passed and doSomething has already executed by then which means that when doSomething executes nbwidg will be 0 since OnDataReceived hasn't happened yet, but on FixedUpdate, which happens later, the correct value will already be set.
Case #2: At Start, that if check inside OnDataReceived evaluates to false, so nbwidg won't be set. But then OnDataReceived is called again some time later and that if now evaluates to true so you get the expected value in FixedUpdate.
That's what I can conclude about the code shown. If you show more, pinpointing the issue will be easier.
Edit: Also, just to clarify, nbwidg, is not a global variable. It is a private field of a class instance.
Answer by Pulsar19 · Dec 17, 2018 at 07:25 PM
Thank you for your answer ! But the problem is that OnDataReceived is called before... Because I need OnDataReceived to create my scene in Unity. And I verified and I try "Debug.Log" => The condition ''if'' of my OnDataReceived is called before (evaluates to true).
It is why I dont understand, it's very strange :-(
If your replace that body with:
private int nbwidg;
void Start()
{
OnDataReceived();
doSomething();
}
void OnDataReceived()
{
if (true)
{
Debug.Log("Setting value!");
nbwidg = 5;
}
}
void doSomething()
{
Debug.LogFormat("Using value! :: {0}", nbwidg);
for (int i = 0; i < nbwidg; i++)
{
Debug.LogFormat("i: {0}", i);
}
}
what happens?
doesn't work, nbwidg = 0 in doSomething and it doesn't enter in the condition for
So OnDataReceived
sounds like an implementation of an interface function. Can you link the class declaration?
Your answer
![](https://koobas.hobune.stream/wayback/20220612184150im_/https://answers.unity.com/themes/thub/images/avi.jpg)