1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- using UnityEngine;
- using System.Collections;
- using System.Collections.Generic;
- namespace TrafficSimulation{
- public class CarSituationSpawner : MonoBehaviour
- {
- public float spawnRate = 5.0f;
- public Transform[] spawns;
- public PresetTrigger[] despawns;
- public CarPool carPool;
- private List<IEnumerator> coroutines = new List<IEnumerator>();
- private bool isActive;
- private List<GameObject> cars = new List<GameObject>();
- // Use this for initialization
- void Start()
- {
- this.isActive = false;
- }
- // Update is called once per frame
- void Update()
- {
- if(this.isActive){
- CheckDespawns();
- }
- }
- void OnDestroy() {
- StopSpawning();
- }
- public void StartSpawner(){
- Debug.Log("Start Spawner");
- this.isActive = true;
- StartSpawns();
- }
- public void StopSpawner(){
- this.isActive = false;
- StopSpawning();
- DespawnAllCars();
- }
- private void CheckDespawns(){
- Debug.Log("Check for despawn");
- foreach(PresetTrigger despawn in despawns){
- if(despawn.checkLastTrigger()){
- DespawnCar(despawn.getLastCollider());
- }
- }
- }
- private void StartSpawns(){
- Debug.Log("Start Spawns");
- foreach(Transform spawnPos in spawns){
- IEnumerator coroutine = AutoSpawning(spawnPos);
- this.coroutines.Add(coroutine);
- StartCoroutine(coroutine);
- }
- }
- private void DespawnAllCars(){
- foreach(GameObject car in this.cars){
- DespawnCar(car);
- }
- }
- private void StopSpawning(){
- foreach(IEnumerator coroutine in this.coroutines){
- StopCoroutine(coroutine);
- }
- }
- void SpawnCar(Transform carSpawn){
- Debug.Log("despawnCars");
- this.cars.Add(this.carPool.SpawnCar(carSpawn));
- }
- void DespawnCar(GameObject car){
- Debug.Log("despawnCars");
- this.carPool.despawnCar(car);
- }
- public IEnumerator AutoSpawning(Transform position){
- while(true){
- SpawnCar(position);
- yield return new WaitForSeconds(this.spawnRate);
- }
- }
- }
- }
|