Spawn Random Prefab Continuously?
I wrote a piece of code but I would like it to spawn one out of two prefabs every 4 seconds. NO matter what I try and where I look I just can't do it. Help would be greatly appreciated. Thanks. (the second variable is redball) using UnityEngine; using System.Collections; public class BallSpawner : MonoBehaviour { public GameObject purpleball; public float delayTime = 4f; IEnumerator Start() { var obj = Instantiate(purpleball, transform.position, transform.rotation) as GameObject; yield return new WaitForSeconds(delayTime); StartCoroutine(Start()); } }
Answer by DroidifyDevs · Apr 17, 2016 at 03:49 PM
Read this; http://docs.unity3d.com/ScriptReference/Object.Instantiate.html And this: http://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
I use this to instantiate: Instantiate(BotToSpawn1, new Vector3(375,0,800), Quaternion.identity);
So something like this should work
void Start
{
StartCoroutine(Spawn1());
}
IEnumerator Spawn1()
{
yield return new WaitForSeconds(4);
//change new Vector3(XXX, XXX, XXX) with wherever you're spawning
Instantiate(YourThingHere, new Vector3(375,0,800), Quaternion.identity);
StartCoroutine(Spawn2());
}
IEnumerator Spawn2()
{
yield return new WaitForSeconds(4);
//change new Vector3(XXX, XXX, XXX) with wherever you're spawning
Instantiate(YourThingHere, new Vector3(375,0,800), Quaternion.identity);
StartCoroutine(Spawn1());
}