Adding a timer on my spawn script
I basically want to add a timer on my spawn script, my spawn script spawn an object once you start the game. i want to change this so once 20 (or more) seconds has pass then it starts spawning. can anyone please help me. Thank you. Here's my script:
using UnityEngine;
using System.Collections;
/// <summary>
/// Spawns a prefab randomly throughout the volume of a Unity transform. Attach to a Unity cube to visually scale or rotate. For best results disable collider and renderer.
/// </summary>
public class DONE : MonoBehaviour {
public GameObject ObjectToSpawn;
public float RateOfSpawn = 1;
private float nextSpawn = 0;
// Update is called once per frame
void Update () {
if(Time.time > nextSpawn)
{
nextSpawn = Time.time + RateOfSpawn;
// Random position within this transform
Vector3 rndPosWithin;
rndPosWithin = new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), Random.Range(-1f, 1f));
rndPosWithin = transform.TransformPoint(rndPosWithin * .5f);
Instantiate(ObjectToSpawn, rndPosWithin, transform.rotation);
}
}
}
Answer by flashframe · Sep 22, 2015 at 07:01 PM
You can use Invoke() or a Coroutine to call a function after a set amount of time has passed. http://docs.unity3d.com/ScriptReference/MonoBehaviour.Invoke.html
In this case you could move your spawning logic from the Update() function into a function called Spawn() and just invoke that function when you need to.
For example:
public float SpawnDelay = 20f;
void Start(){
Invoke("Spawn", SpawnDelay);
}
void Spawn () {
// Random position within this transform
Vector3 rndPosWithin;
rndPosWithin = new Vector3(Random.Range(-1f, 1f), Random.Range(-1f, 1f), Random.Range(-1f, 1f));
rndPosWithin = transform.TransformPoint(rndPosWithin * .5f);
Instantiate(ObjectToSpawn, rndPosWithin, transform.rotation);
Invoke("Spawn",SpawnDelay);
}
You could also just use Invoke Repeating in the start function, to avoid having to call it again in the spawn function.
InvokeRepeating("Spawn", SpawnDelay);
See the Unity Learn tutorials for more info: https://unity3d.com/learn/tutorials/modules/beginner/scripting/invoke
Your answer
Follow this Question
Related Questions
How can I make an object clone in the time that I indicate it to appear? 0 Answers
I HAVE TWO ERROR ONE IN StartCoroutine(SpawnBigTree()); AND ONE ON FLOAT 0 Answers
My gameObject (enemy) is being spawned rapidly to the point of crashing, how do I fix this? 0 Answers
[c#] Increase speed of instantiating over time!? 1 Answer
Gaps between path spawns 0 Answers