CarSituationSpawner.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using UnityEngine;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. namespace TrafficSimulation{
  5. public class CarSituationSpawner : MonoBehaviour
  6. {
  7. public float spawnRate = 5.0f;
  8. public Transform[] spawns;
  9. public PresetTrigger[] despawns;
  10. public CarPool carPool;
  11. private List<IEnumerator> coroutines = new List<IEnumerator>();
  12. private bool isActive;
  13. private List<GameObject> cars = new List<GameObject>();
  14. // Use this for initialization
  15. void Start()
  16. {
  17. this.isActive = false;
  18. }
  19. // Update is called once per frame
  20. void Update()
  21. {
  22. if(this.isActive){
  23. CheckDespawns();
  24. }
  25. }
  26. void OnDestroy() {
  27. StopSpawning();
  28. }
  29. public void StartSpawner(){
  30. Debug.Log("Start Spawner");
  31. this.isActive = true;
  32. StartSpawns();
  33. }
  34. public void StopSpawner(){
  35. this.isActive = false;
  36. StopSpawning();
  37. DespawnAllCars();
  38. }
  39. private void CheckDespawns(){
  40. Debug.Log("Check for despawn");
  41. foreach(PresetTrigger despawn in despawns){
  42. if(despawn.checkLastTrigger()){
  43. DespawnCar(despawn.getLastCollider());
  44. }
  45. }
  46. }
  47. private void StartSpawns(){
  48. Debug.Log("Start Spawns");
  49. foreach(Transform spawnPos in spawns){
  50. IEnumerator coroutine = AutoSpawning(spawnPos);
  51. this.coroutines.Add(coroutine);
  52. StartCoroutine(coroutine);
  53. }
  54. }
  55. private void DespawnAllCars(){
  56. foreach(GameObject car in this.cars){
  57. DespawnCar(car);
  58. }
  59. }
  60. private void StopSpawning(){
  61. foreach(IEnumerator coroutine in this.coroutines){
  62. StopCoroutine(coroutine);
  63. }
  64. }
  65. void SpawnCar(Transform carSpawn){
  66. Debug.Log("despawnCars");
  67. this.cars.Add(this.carPool.SpawnCar(carSpawn));
  68. }
  69. void DespawnCar(GameObject car){
  70. Debug.Log("despawnCars");
  71. this.carPool.despawnCar(car);
  72. }
  73. public IEnumerator AutoSpawning(Transform position){
  74. while(true){
  75. SpawnCar(position);
  76. yield return new WaitForSeconds(this.spawnRate);
  77. }
  78. }
  79. }
  80. }