Issues with randomly moving a cube

I’m trying to move a cube randomly every 2 seconds. When I press play 2 seconds passes, and then the cube starts moving every frame.

#pragma strict

var waitTime : float = 2 ;

function Start () {

}

function Update () {
MoveCube();
}


function MoveCube(){
yield WaitForSeconds (waitTime);
var position = Vector3(Random.Range(-6,6), Random.Range(-4,4), 0);
transform.position = position;
}

I’m very new to Unity so I’m sure the answer is pretty simple. Thanks

Hi Overx, that issue happens because MoveCube() is called every frame. You can use a locking mechanism: with that, you perform MoveCube() only if the last execution is over. Just modify the script as follows:

#pragma strict

var waitTime : float = 2;
var move_lock = false;

function Start () {

}

function Update () {
if (!move_lock)
   MoveCube();
}


function MoveCube(){
move_lock = true;
yield WaitForSeconds (waitTime);
var position = Vector3(Random.Range(-6,6), Random.Range(-4,4), 0);
transform.position = position;
move_lock = false;
}

Please remember that the function Update is called every frame. You may want to use InvokeRepeating but don’t call it in the update, otherwise it will have a take a repeating calls to a method/function.

With your code, yielding WaitForSeconds was called every frame(however many you get per second) which is why your cubes continued to move, while you were thinking it would wait 2 seconds and do it, but if it ran 30 frames a second, then the WaitForSeconds yield was called 30 times. :slight_smile:

InvokeRepeating will only need to be called once and as the method/function name suggests, will continue repeating based off the time/repeat rate you gave it.

Previous answers are good. If you want to keep using coroutine, you need to start the repeating coroutine in a loop inside the Start method:

// JS
var someBoolean = true;
function Start()
{
    while( someBoolean )
    {
        yield StartCoroutine(MoveCube());
    }
}

// C#
bool someBoolean = true;
IEnumerator Start()
{
    while( someBoolean )
    {
        yield return StartCoroutine(MoveCube());
    }
}