- Home /
how to instantiate an object every second?
hello. i just wanted to know how to instantiate a object every second? (in this case a laser beam) i have tried using Time.deltaTime, but it still isn't playing ball. (when debugging(on fastest), it still is firing alot faster then in the editor?).
i've even tried invokeRepeat(function(string),time(int), seconds (int)) but still no joy? how do i get unity to do a certain thing at a consistent speed on any computer! i could try fixedUpdate but i don't really fancy separating if(GetAxis("Fire1")) in too two functions as it will overload a first animation i have.
Answer by Mickydtron · Dec 16, 2010 at 07:23 PM
try having a variable store the last time you fired. then you can check if a second has passed, and if it has, fire and set the last fired time to now.
var lastFired = 0.0;
if(( Time.time > lastFired + 1.0)&&(GetAxis("Fire1"))
{
//fire lasers!
lastFired=Time.time;
}
Answer by Statement · Dec 16, 2010 at 08:18 PM
i've even tried invokeRepeat(function(string),time(int), seconds (int)) but still no joy?
var laserPrefab : GameObject; var timeBetweenLasers : float = 0.5f;
function Update() { if (Input.GetButtonDown("Fire1")) InvokeRepeating("FireLaser", float.Epsilon, timeBetweenLasers); if (Input.GetButtonUp("Fire1")) CancelInvoke("FireLaser"); }
function FireLaser() { if (!laserPrefab) { Debug.LogWarning("You forgot to set the laser prefab!"); return; }
Instantiate(laserPrefab, transform.position, transform.rotation);
}
The float.Epsilon (smallest positive float value) is there because if you have 0, for some reason you get 3 calls to FireLaser in case you tap the button.
Your answer
Follow this Question
Related Questions
Physics behaviour changing with framerate - Is FixedUpdate() actually working properly? 3 Answers
Camera rotate around a moving object: fixedLateUpdate? 1 Answer
Is it possible to create a second FixedUpdate function running at different rate? 2 Answers
Fixed Update Time, Object Stop moving 0 Answers
FixedUpdate and LineCast? 0 Answers