Hi everyone, I've been at this all day, but have not found an ideal solution. Please bear with me as I am new to Unity. I have made a simple game space shooter type game. I have one character that falls down the screen, and if it collides with the player, the player gets a life added to him. Right now, as soon as the extra life character falls below the camera view, he is automatically respawned at a random location on top and falls back down the scree. My question is, how can I delay the time between spawns of this "extra life" character? Right now, my javascript for the "extra life" character is:
You could use WaitForSeconds. I recall it beeing used differently with js than from c# which I use so can't really make an example with your code but here's the unity api for it:
var lifegermSpeed: int;
var canEnter : boolean;
function Update () {
// prevent MoveAndSpawn() from being called if the 10 seconds timer is running
if (canEnter)
MoveAndSpawn();
}
}
function MoveAndSpawn()
{
amtToMove = lifegermSpeed * Time.deltaTime;
transform.Translate(Vector3.down*amtToMove);
if(transform.position.y <=-3){
transform.position.y = 20;
transform.position.x = Random.Range(-6,6);
canEnter = false;
yield WaitForSeconds(10.0);
}
// can enter this function again
canEnter = true;
}
You cannot use co-routine in Update(). Move your logic to a new function and call it from within Update(). However, as Update() is called every frame, you need a flag to prevent MoveAndSpawn() to be called again before the 10 seconds is done.
I would suggest that you separate the logic for moving and for re-spawning the life up,though.
do not do this, it will start a new coroutine every frame. Under the hood, javascript will make MoveAndSpawn return an IEnumerator. To fix this code you shouldmake yet another function that is called within the if statement. That function should set the value of canEnter and the yield keyword. In that case you can move the rest of the code directly into Update.
do not do this, it will start a new coroutine every frame. Under the hood, javascript will make MoveAndSpawn return an IEnumerator. To fix this code you shouldmake yet another function that is called within the if statement. That function should set the value of canEnter and the yield keyword. In that case you can move the rest of the code directly into Update.
– loopyllama@harmless. Of course you're correct. Thanks for spotting my oversight. I have changed the code.
– Extrakun@Extrakun rock on! @Elaine use this code!
– loopyllama