Question by
leorfanell · Nov 18, 2018 at 08:39 PM ·
method
How to call a method only once after some time has elapsed?
I have this code:
public class spawnObstacle : MonoBehaviour {
public GameObject storm, lightningStrike1, lightningStrike2;
public float time = 0f;
// Update is called once per frame
void Update () {
time += Time.deltaTime;
}
// find out how to spawn it only once
// can't be placed on Update, or else
// it'll spawn it infinetly
void SpawnStorm() {
if (time >= 5) {
Instantiate(storm, transform.position, Quaternion.identity);
}
}
void SpawnLightningStrikes() {
if (time >= 6.2f) {
Instantiate(lightningStrike2, transform.position, Quaternion.identity);
}
if (time >= 7f) {
Instantiate(lightningStrike1, transform.position, Quaternion.identity);
}
}
}
I want to spawn the gameObjects I declared (hence the methods), but if I place it on Update(), it is called once every frame after the condition is met. How can I make it so that it is called only once after the condition is met? I'm a beginner on Unity, so any help/mentoring is greatly appreciated!
Comment
Answer by Twistyd · Nov 19, 2018 at 10:56 AM
Try using a separate spawn function and InvokeRepeating or Invoke to call it.
https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html
https://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html
An example of the InvokeRepeating would be;
public float timeBetweenSpawns =1.2f;
void Start(){
InvokeRepeating ("Spawn", 0f, timeBetweenSpawns);
}
public void Spawn(){
// Your spawning function goes in here
}
But set the time to something high so you only get the expected effect the once, when you want it . Hope it helps.