using System.Collections; using UnityEngine; public class Spawner : MonoBehaviour { //GameObjects Variabes public GameObject Object1; // Insert cube here public Transform spawnBox; //gives us position, rotation,scale of spawnbox //Changing Variables public float SpawnTime = 1f; public int MaxNoOfObjects = 5; public static bool objectDestroyed = false; //global Variable void Start() { //Start Spawning objects StartCoroutine(spawnLoop()); } void Update() { if (objectDestroyed) { objectDestroyed = false; createObj(); } } public GameObject createObj() { //This function will spawn an obj //get random position within a space Vector3 randomPos = getRandomPos(); //Instantiate(object, position, rotation, parent, instantiateInWorldSpace //this will spawn an object GameObject newObj = Instantiate(Object1, randomPos, Quaternion.identity) as GameObject; return newObj; } public Vector3 getRandomPos() { //get random position within the spawnBox //Spawnbox area float MIN_X = -spawnBox.localScale.x / 2, MAX_X = spawnBox.localScale.x / 2; float MIN_Y = -spawnBox.localScale.y / 2, MAX_Y = spawnBox.localScale.y / 2; float MIN_Z = spawnBox.position.z - (spawnBox.localScale.z / 2), MAX_Z = spawnBox.position.z + (spawnBox.localScale.z / 2); float x = UnityEngine.Random.Range(MIN_X, MAX_X); float y = UnityEngine.Random.Range(MIN_Y, MAX_Y); float z = UnityEngine.Random.Range(MIN_Z, MAX_Z); Vector3 pos = new Vector3(x, y, z); return pos; } private IEnumerator spawnLoop() { yield return new WaitForSeconds(2); //Wait for 5 seconds int i = 0; while (i < MaxNoOfObjects) { createObj(); i++; //Wait for awhile before spawning the next object float randomSpawnTime = Random.Range(SpawnTime, SpawnTime * 2); yield return new WaitForSeconds(randomSpawnTime); } } }