- Home /
Other
A Simple Spawning System Code.
This is what i have so far but im planing on change the code. this code help's spawn the car but it spawns at a specific time so like every 5 secs or so. Im trying to make it so the car only spawn one at a time until it despawns the next one will spawn after it.
using UnityEngine;
using System.Collections;
public class CarController : MonoBehaviour {
public GameObject enemy;
public Vector3 spawnValues;
public int enemyCount;
public float spawnWait;
public float startWait;
public float waveWait;
void Start ()
{
StartCoroutine (SpawnWaves ());
}
IEnumerator SpawnWaves ()
{
yield return new WaitForSeconds (startWait);
while (true)
{
for (int i = 0; i < enemyCount; i++)
{
Vector3 spawnPosition = new Vector3 (Random.Range (-spawnValues.x, spawnValues.x), spawnValues.y, spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (enemy, spawnPosition, spawnRotation);
yield return new WaitForSeconds (spawnWait);
}
yield return new WaitForSeconds (waveWait);
}
}
}
Rather than instantiating a new object could you just recycle the old one if you only ever want one on the screen, If you want more then just have a pool of objects that you draw from so you can have up to a maximum number of cars. You don't really need to create a new Coroutine for this either, and I$$anonymous$$HO the CarController should not spawn itself. There should be a WorldController or similar that checks the state of all your game objects in Update()
and updates them accordingly (a car should know if it is alive or not). Then spawning simply becomes a matter of removing already instantiated objects from the scene and returning them to the pool only to be attached again when you want one to spawn. Does this sound like what you are trying to achieve?
Answer by Mark Gossage · Jun 24, 2015 at 05:51 AM
Two ways you could do this:
Have a static variable in the Car script which increments when a Car is Start()ed, and decrements it when the Car is Destroy()ed. Then the spawner can just look at the Car counter to decide if it wants to spawn or wait.
Have only one Car & recycle it. Instead of destroying it, just call gameObject.SetEnabled(false) to make it vanish. The spawn script can just check if the Car is obj.IsActive and recycle it if it is not.
The second is better, but will only work if you want one car. If you want more than one, go to the unity life training achieve and look up Object Pooling.
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Spawning A Grid Of Cubes 2 Answers
Trying to make a spawning enemy code 1 Answer
How to spawn objects in areas that are only created at run time? 0 Answers