Hello everyone!
I’ve got a question about how code will be executed when I try to do the following:
void Update () {
DoSomethingA();
}
void DoSomethingA () {
for (int i = 0; i < 10; i++) {
DoSomethingB(i);
}
}
int someInt = -1;
void DoSomethingB (int i1) {
someInt = i1;
// doing some stuff
}
Could someInt already be set to the next value while “doing some stuff” hasn’t finished with the previous value?
Or will DoSomethingB(1){} always be executed completely before DoSomethingB(2){}?
Also, what about using Start(){} instead of Update(){}? Will there be a difference?
Will I have to use “yield return null” in any of these for loops?
void Start () {
DoSomethingA();
}
void DoSomethingA () {
for (int i = 0; i < 10; i++) {
DoSomethingB(i);
}
DoSomethingA();
}
int someInt = -1;
void DoSomethingB (int i1) {
someInt = i1;
// doing some stuff
}
Also, maybe this question could be reduced to this (, couldn’t it?):
void Update () {
StuffToDo1();
StuffToDo2();
}
Will StuffToDo1() always finish completely before StuffToDo2() even starts? Or this version, using Start():
Variables in the class scope are always initialized first before running methods, regardless of their place in the script. Generally good practice dictates you put them at the top of the script.
I think there are some thread safe exceptions that others might need to clarify for you but afaik the methods are processed completely before moving to the next line. If method a sets some class scope variable, then runs method b, you can be sure the variable will be set before b runs.
@LaneFox
Thank you for your reply! I didn’t actually mean the declaration of the variable, but only at which time it will be changed by the methods and whether or not a method “stops” execution when it calls another method and keeps going when that other method is finished.
I asked a similar question once and coroutines seem to interfere when there is a problematic yield statement in them.
For example, this would cause problems:
IEnumerator DoStuff () {
while (true) {
StartCoroutine(DoSomething1());
StartCoroutine(DoSomething2());
yield return new WaitForSeconds(2.0f);
}
}
int someInt = -1;
IEnumerator DoSomething1 () {
someInt = 1;
yield return new WaitForSeconds(1.0f);
Debug.Log(someInt.ToString());
}
IEnumerator DoSomething2 () {
yield return new WaitForSeconds(0.5f);
someInt = 2;
}
Now, debug should log “2”, because DoSomething2() was executed while DoSomething1() was paused.
It could not; there is no threading in Unity scripting, at all, ever. (Unless you do your own threading using System.Threading, then it’s up to you to make sure that functions and variables don’t step on each other, and it’s very easy to introduce hard-to-find bugs, so avoid doing threaded code unless you really need it. It’s certainly not something Unity would inflict on the general userbase, especially not without telling anyone, even if the Unity API could be used in threads.)
yield will prevent the code from progressing, but only when instructed as a yield. The example code is very impractical, the first coroutine will run both other coroutines, which are going to run entirely independent of each other and fight over simultaneous timings of setting the same variable - a horrifyingly bad design and therefore difficult to understand what you are expecting to accomplish by doing anything remotely similar.
What exactly are you trying to understand? A more specific question would be helpful to answering your questions clearly.
@Eric5h5
Thank you for your reply! This answered my question!
@
I just wanted to understand in what order the code is being executed.
But as Eric5h5 stated, it is strictly linear. Unless I am using coroutines, that is. Sometimes I am using multiple coroutines at once. In that case, they don’t get executed one after another but at the same time.
For reference, you can take a look at the issues I ran into when asking the following question:
It doesn’t seem to be the best way of designing code, though, because obviously it can cause issues.
Nope, still linear and no threads. It’s certainly possible to write coroutines in such a way as to make it difficult to figure out the order in which things are executed, but it’s not possible for them to execute at the same time.
@Eric5h5
Thanks for correcting! I guess I have been doing something else wrong, then!
It’s good to know it’s going to work linearly even with coroutines.
Sometimes I even tried to write code so that there couldn’t be any methods / coroutines running in parallel, but obviously that optimization was useless!
If Unity worked through things in a straight manner, it would debug
Coroutine01: 1
Coroutine02: 1
Coroutine02: 2
Coroutine01: 2
I just tried to use some for loops based on conditions, so I wanted to branch off some coroutines from a bigger one, but I can’t seem to do so.
Because the execution order will jump back to the main coroutine while branched-off coroutines are still running.
On a more abstact level, this is what I’d have to do:
IEnumerator MainCoroutine () {
if (someCondition) {
for (int i = 0; i < 25; i++) {
// a lot of code
}
}
else {
for (int i = 1; i < 25; i++) {
// a lot of code (same as "a lot of code" before)
}
}
}
Can’t I simplify this?
If there wouldn’t be any jumping back to the MainCoroutine, I would write:
IEnumerator MainCoroutine () {
if (someCondition) {
for (int i = 0; i < 25; i++) {
StartCoroutine(ALotOfCode(i));
}
}
else {
for (int i = 1; i < 25; i++) {
StartCoroutine(ALotOfCode(i));
}
}
}
IEnumerator ALotOfCode (int i) {
// a lot of code
}
The thing is, I need to set different values in the for loop declaration depending on a condition.
If I cannot do this, I have to copy all the code contained in the for loop, which makes it hard to maintain.
(See MainCoroutine’s first example)
Is there anything like
for (if (someCondition) {int i = 0} else {int i = 1}; i < 25; i++) {}
No, that would be very wrong and unexpected. Your code prints “01: 1”, starts coroutine 2 which prints “02: 2”, waits 1 second in coroutine 1 and prints “01: 2”, then 3 seconds later (since coroutine 2 is waiting 4 seconds), prints “02: 2”. The debug log is 100% correct.
So waiting will change the order.
I am not saying it’s unexpected, it’s just hard to work with in certain situations like the one I described.
Of course, most situations greatly benefit from that behavior.
But if you want to branch off coroutines, it’s hard to manage, isn’t it?
EDIT:
Well, maybe not:
bool mainCoroutineWait = false;
IEnumerator MainCoroutine () {
if (someCondition) {
for (int i = 0; i < 25; i++) {
mainCoroutineWait = true;
StartCoroutine(ALotOfCode(i));
while (mainCoroutineWait) {yield return null;}
}
}
else {
for (int i = 1; i < 25; i++) {
mainCoroutineWait = true;
StartCoroutine(ALotOfCode(i));
while (mainCoroutineWait) {yield return null;}
}
}
}
IEnumerator ALotOfCode (int i) {
// a lot of code
mainCoroutineWait = false;
}
Of course. But if you tell Unity to wait for a period of time in a coroutine, it’s kind of hard to complain that it does exactly what you tell it to, no?
Are you trying to chain coroutines? Any reason why you wouldn’t just use yield return StartCoroutine?
@Eric5h5
Yes, it does wait on Coroutine02. But while Unity waits on Coroutine02, it does continue on Coroutine01. So if it was executed line by line, it wouldn’t jump back to 01 while 02 is paused, right?
I didn’t know about yield return new StartCoroutine. What is to be expected from this?
Does it wait until said coroutine is finished?
Yes, I want to execute multiple coroutines while other coroutines are running.
However, the “host coroutine” is supposed to wait until the coroutine it started is finished.
I just found something similar in the documentation.
There, “yield StartCoroutine()” is used to wait until the coroutine is finished: