I was reading the Unity scripting guide on this and they suggested using yields and coroutines. However, they mentioned that it doesn’t work in an Update or FixedUpdate function and that’s exactly where I think I need to use it (I am a beginner, I could be totally wrong).
I’m trying to get a block to randomly choose a direction and go in that direction for a given amount of time. However, for some reason it won’t execute the entire turning function (e.g. when I tell it to turn 90 degrees it seems to only turn 3 before randomly choosing another direction). My code thus far looks like this:
var direction:int;
var degrees:float;
function Update ()
{
direction = Mathf.Floor(Random.value * 4);
switch(direction)
{
// move forward
case 0:
StartCoroutine(moveForward());
break;
// make a 180 and move forward
case 1:
StartCoroutine(turn(-180));
StartCoroutine(moveForward());
break;
// turn right and move forward
case 2:
StartCoroutine(turn(90));
StartCoroutine(moveForward());
break;
// turn left and move forward
case 3:
StartCoroutine(turn(-90));
StartCoroutine(moveForward());
break;
}
}
function moveForward ()
{
transform.Translate(0, 0, 2 * Time.deltaTime);
yield WaitForSeconds(5);
}
function turn (degrees)
{
transform.Rotate(0, degrees * Time.deltaTime, 0);
yield WaitForSeconds(5);
}
Any help would be much appreciated, thank you!