- Home /
Could Update and FixedUpdate happen at the same time?
Just a simple question, could Update and FixedUpdate happen at the same time?
Update:
a = 1; b = a;
Fixed Update:
a = 2; b = a;
Could b become 2 in update as an example?
They could at best run on the same frame if your computer happens to run exactly on the same speed as the FixedUpdate and never fluctuate.
Answer by Benproductions1 · Feb 16, 2014 at 05:53 AM
The only way anything on a computer can happen "at the same time" is if you have multiple processors on the same computer. The only way you can have a single program run on more than one processor is to use threads. Threads are very special with memory management, because they can access mutable variables. A thread cannot mutate a variable from another thread without a possible segmentation fault.
Update
and FixedUpdate
both run on the same thread, so no... they can never run at the same time.
With that code, b will always equal 1 in the Update, as it is set right before b is assigned. Consider this case where a & b are both fields in our class:
//in Update
b = a;
a = 1;
Debug.Log(b); //might print 2 or 1, assu$$anonymous$$g no other assignments are done to a
// in Fixed Update:
a = 2;
b = a;
Debug.Log(b); //always prints 2
While true, they cannot run at precisely the same time, the execution order of events is that FixedUpdate is always run before any Update. However, FixedUpdate might not get called before every Update.
It is thus possible for b to equal 2 in some calls to Update, but not in others. It depends on whether a FixedUpdate was run before or not.
The same effect is achieved with just:
//update
Debug.Log(a);
a = 1;
//fixed update
a = 2;
Debug.Log(a);
This will obviously cause problems simply because of assignment rules and the fact that code is executed in order. I don't see how that's relevant to the question?
If this were C the compiler would even throw warnings because you'd be using a variable before assignment. I think the same goes for C++
Let's say they are public variables assigned before any methods. And that obviously can happen.
Also, in the example I showed above, you don't need to have 2 threads, so threads are not really the question here.
Threads are just used to explain why update and fixed update can't possibly run at the same time. They are simply a means to an end.
Again the example given by @Jamora is just another example of how side effects can cause problems. It pertains to every single function and is a perfect example of badly planned program$$anonymous$$g (of it does occur). It doesn't have much to do with the question: Whether Update and Fixed Update van run simultaneously.