- Home /
Randomize Spawn Time
How can I randomize the Spawn time so that the object is spawned at different intervals of time from the same location.`enter code here` Thank You.
public GameObject Obj;
// Use this for initialization
void Start () {
StartSpawn ();
}
// Update is called once per frame
void Update () {
}
public void StartSpawn(){
InvokeRepeating ("SpawnObj", 0.2f, 1f);
}
void SpawnObj()
{
Instantiate(Obj, new Vector3(transform.position.x,transform.position.y, Quaternion.identity);
}
}
Answer by · Oct 24, 2017 at 05:20 PM
I dont know if you can change the time form a InvokeRepeating. You can use Coroutine. Something like This:
public GameObject Obj;
// Use this for initialization
void Start () {
StartSpawn ();
}
// Update is called once per frame
void Update () {
}
public void StartSpawn(){
StartCoroutine("SpawnObj");
}
IEnumerator SpawnObj()
{
Instantiate(Obj, new Vector3(transform.position.x,transform.position.y, Quaternion.identity);
yield return new WaitForSeconds(Random.Range(5.0f, 10.0f));
StartCoroutine("SpawnObj");
}
}
https://docs.unity3d.com/ScriptReference/Coroutine.html https://docs.unity3d.com/ScriptReference/Random.Range.html
This works perfectly. Thank You. But I knew this method. I wanted to see if you could Randomize the spawn time in the InvokeRepeating function!
Answer by leSamo · Oct 24, 2017 at 05:20 PM
You can use UnityEngine.Random to generate random values. Use
Random.value
to get a random float between 0 and 1, or use
Random.Range(int a, int b)
to get a random integer between a (inclusive) and b (inclusive).
Your answer
Follow this Question
Related Questions
Spawning objects at points within another object? 1 Answer
Instantiate Prefab at random 1 Answer
Spawn Object On Empty Object Location Different Each Time Game Starts 2 Answers
Randomize Spawn Times 0 Answers
2D runner, need a help 0 Answers