- Home /
How to Instantiate prefabs with function Update?
Hello everyone, I'm developing a 2D shoot-em-up android game where the player controls a spaceship and must avoid incoming meteoroids as long as possible. I manage to get all the core mechanics completed (movement and enemy spawning) and now currently working on some power-ups.
I'm working on implementing a slow down/slow motion power up that effects the gravity scale of the enemy, and so I've decided to re-work my spawning script.
var delay : float;
var enemy : GameObject;
var rightSpawn : float;
var leftSpawn : float;
function Start () {
InvokeRepeating ("Spawn",delay,delay);
}
function Spawn () {
yield WaitForSeconds (delay);
Instantiate (enemy, new Vector3 (Random.Range (rightSpawn,leftSpawn),10,0), Quaternion.identity);
}
As you can see above I'm using the InvokeReating
to instantiate meteroids (enemy) every 0.27 seconds (delay).
I know I could just make another series of script that gets called using a Time.deltatime
to achieve my goal, but if I could somehow manage to change or convert this script to an update function, changing the float variables or any other components such as the gravity will be must more easier.
Therefore I was wondering if anyone has an idea on how I could possibly achieve this?
I'm not sure what you want here? What do you mean by 'change or convert this script to an update function'? Also, there are no variables to control gravity or anything else here, only a line to spawn an enemy at some position every 0.27s.
Answer by robertbu · Jan 17, 2014 at 06:06 AM
First your use of 'yield' in your current Spawn() function is not necessary. As for an Update() version of this code, consider using a timestamp. You set a timestamp to some future time. When Time.time is >= to your timestamp, you trigger the event and then recalculate for a future event:
#pragma strict
var delay : float;
var enemy : GameObject;
var rightSpawn : float;
var leftSpawn : float;
private var timestamp = 0.0;
function Update () {
if (timestamp <= Time.time) {
timestamp = Time.time + delay + (Time.time - timestamp);
Instantiate (enemy, new Vector3 (Random.Range (rightSpawn,leftSpawn),10,0), Quaternion.identity);
}
}
Hey, thank you, this works perfectly and finally I can continue on developing my game!