- Home /
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
Writing "answered" in the title doesn't mark a question as answered, you need to do that by clicking the checkmark.
Answer by BiG · Dec 11, 2012 at 03:04 PM
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;
}
@Overx, can you please mark the question as answered, as the guys suggest? You simply need to click on the green symbol at the left of my question (or at the left of the question that you find more useful). Thank you.
Answer by Landern · Dec 11, 2012 at 03:07 PM
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. :)
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.
Answer by Kryptos · Dec 11, 2012 at 04:03 PM
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());
}
}