Unity Hangs while calling another function in start

Hi, I ran into an issue in which Unity hangs when i try to call function “test” in the “start” function. I’m unsure why and any advice will be greatly appreciated.

using UnityEngine;
using System.Collections;
using System;



//public KeyCode KeyCode.Alpha2;


public class Test : MonoBehaviour {

	public Boolean trigger = false;
	public HUDText hudText;



	void Start(){

		StartCoroutine(MyCoroutine());

	
		}
	
		

	IEnumerator MyCoroutine()
	{
		hudText.Add("Welcome", Color.white, 3f);

		yield return new WaitForSeconds(3);    //Wait one frame
		
		hudText.Add("This is System Defence", Color.white, 4f);

		yield return new WaitForSeconds(4);

		hudText.Add ("Try using WASD to move", Color.red, 3f);
		
		yield return new WaitForSeconds(3);



		}

	void test() {

			 while(trigger == false) {
						if (Input.GetKeyDown (KeyCode.W) 
								| Input.GetKeyDown (KeyCode.A)
								| Input.GetKeyDown (KeyCode.S)
								| Input.GetKeyDown (KeyCode.D)) {
								hudText.Add ("Nice work! Now try...", Color.red, 3f);
								
				 				Debug.Log (trigger);
								
								trigger=true;

								
							}
				}
		Debug.Log (trigger);
		}
}

Yep, it will hang, but not because the function is called from Start(). Any call to test() would hang your app. The problem is that test() is not a coroutine, and you don’t yield. That means Unity is never given control to collect keyboard input, which means that ‘trigger’ is never set to true. So you have an infinite loop hanging your app.

One solution is to make test() a coroutine and put:

yield return null;

…inside the while loop.

Note that you can make Start() an IEnumerator and put a yield in start. And you can yield on other coroutines.