Why this crashes unity ? [Do While & If]

i writed this script for testin difference between do while and if statement
so why when i hit play the DO float become 2 even if i have the “operate” bool false
and why when i hit play my editor stucks, keeps 50% of my processor usage, and doesn’t let me see the IF float augmenting?

using UnityEngine;
using System.Collections;

public class lala : MonoBehaviour {

	public float DO;
	public float IF;
	public bool operate = false;
	private float DObase = 1f;
	private float IFbase = 1f;

	void Update () {
		do{
			DO = DObase + 1f;
		}while(operate == true);
	 if (operate == true) {
			IF = IFbase + 1f;
		}
	}
}

So you have 2 questions.
The first one is why DO becomes 2.
The second one is why your editor freezes.

The answer to your first question is because you wrote it that way. Do - While will run what’s under Do once and then check if the While conditions are met. So it’s perfectly normal for DO to become 2f when you hit play regardless of what “operate” is.

The answer to your second question is I’m guessing that you manually checked “operate” to be true in the editor. So when the script runs, it goes into an infinite loop trying to add IF and DO to infinity.

update is called once per frame, unity is using something called an update loop. You can imagine somthing like: calling the Update() method from each script and then rendering an image.

if one would write an update() method which takes unusually long, it would slow down the program because it takes longer till unity can render the next image. now imagine someone would write an update method which never ends. unity could never reach the point to render the next frame → the editor freezes.

void Update () {
    do{
        DO = DObase + 1f;
    }while(operate == true);
    if (operate == true) {
        IF = IFbase + 1f;
    }
}

a do{ ... }while(); loop is the same as a while(){ ... } loop, with the difference it will always run at least once. Your loop will be execute till operate gets false, so imagine operate is true when you enter this update loop. operate is never changed in your loop, there are no breaks, so you will never reach a state where your condition in the while-head gets false, so you build an infitiy-loop.

So, lets check what your loop does:

your loop uses the value of DObase (which you’ve set to 1) adds 1 to it, and puts that in the variable DO. so your variable DO is now 2. because DObase does not change, DOBase+1 will always be 2.

also your CPU will get stuck in your do-while loop, so you’ll never reach the line where you want to increment IF


You could try to tell us (maybe in another question) what you want to archive if you need help. Becaues i have no clue what you are trying to do anyway. But i hope this explains what went wrong