Coroutine freezes editor but only sometimes. Why ? Why is it happening randomly ?

Really weird behaviour. At some test runs, this coroutine freezes the unity editor at the point when it is supposed to check if(i == 2), that I have to terminate unity editor via task manager every time. And at other test runs, it runs without any problems without having changed any code. It’s unpredictable for me to why it crashes randomly at that particular if statement. It’s driving me into madness especially since it does work but sometimes it crashes unity without any debug messages are getting printed.
I really need some suggestions. Am I misunderstanding yields or something ? I’m using Unity2019.2.17f1

Edit1: Not crashing, but rather freezing to the point task manager says the editor gives no response. Also added 2nd screenshot how the coroutine is being called. Its always being called once in that scripts lifetime.
Edit2:It’s worthy to mention that the gameobject which houses this script gets destroyed and instantiated as clone. I made sure that there can only one of its kind exist in a scene and also made sure all coroutines on that monobehaviour get stopped OnDestroy.

Are you sure that this Coroutine is not running multiple time.153011-annotation-2020-02-22-102707.png

The fact that you feel you have to run things “at least 3 times” for it to take indicates a problem, because C#/Unity isn’t that random. And in my experience coroutines are a cause for error.

For example in the above answer StartCoroutine could be run more than once because the routine does not start immediately but is put to a list and executed later, so that m_demooroutineisplaying should be set to true before StartCoroutine and not in the coroutine itself to be sure.

If all you do with the coroutine is to wait and set booleans it could be done in Update() with a linear flow in the code.

@rh_galaxy
@kskjadav007
I’ve come in time of great news.
I figured out what was causing the freeze. It wasn’t the coroutine at all. It was a function called SpawnedPuddles() that dwells in the OnEnable of that janitorGame object, which gets set active in posted coroutine.
In SpawnedPuddles(), I used a nested loop, there was a foreach-loop inside a while-loop. The problem in that was the value for the while condition sometimes would never met the condition to false because the value could get into the negative numbers inside the nested foreach-loop. Thanks @Bonfire-Boy for suggesting checking out that object’s script instead. The reason I was sure it must have been something to do with the coroutine was because all logs ended in there and not thinking that when an object gets set active in one frame, all of its Awake, OnEnable and Start codeblocks of that object also gets read in the same frame.

Thanks for the suggestions!