IntersectionPreset.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace TrafficSimulation{
  5. public class IntersectionPreset : MonoBehaviour
  6. {
  7. public TrafficSystem trafficSystem;
  8. public Intersection intersection;
  9. public GameObject cars;
  10. public CarSituationSpawner carSpawner;
  11. public PresetTrigger triggerIn;
  12. public PresetTrigger triggerOut;
  13. public CarPool carPool;
  14. private bool presetRunning;
  15. private List<GameObject> activeCars;
  16. // Start is called before the first frame update
  17. void Start()
  18. {
  19. this.presetRunning = false;
  20. this.activeCars = new List<GameObject>();
  21. }
  22. // Update is called once per frame
  23. void Update()
  24. {
  25. if(triggerIn.checkLastTrigger()){
  26. HandleInTrigger();
  27. }
  28. if(triggerOut.checkLastTrigger()){
  29. handleOutTrigger();
  30. }
  31. }
  32. /// <summary>
  33. /// Starts preset it not already running
  34. /// </summary>
  35. private void HandleInTrigger(){
  36. Debug.Log("In Trigger");
  37. if(this.presetRunning){
  38. Debug.Log("Preset already running");
  39. return;
  40. }
  41. this.presetRunning = true;
  42. SpawnCars();
  43. }
  44. /// <summary>
  45. /// Ends the preset if it was running
  46. /// </summary>
  47. private void handleOutTrigger(){
  48. Debug.Log("Out Trigger");
  49. if(!this.presetRunning){
  50. Debug.Log("Preset wasn´t running, so couldn´t be ended.");
  51. return;
  52. }
  53. this.presetRunning = false;
  54. DespawnCars();
  55. }
  56. /// <summary>
  57. /// If Cars are set, they will be spawned on the given positions. If a carSpawner is set, it will be activated
  58. /// </summary>
  59. private void SpawnCars(){
  60. if(this.cars == null){
  61. Debug.Log("Found no Car Object. Can´t init preset");
  62. return;
  63. }else{
  64. foreach (Transform carSpawn in this.cars.transform)
  65. {
  66. this.activeCars.Add(this.carPool.SpawnCar(carSpawn));
  67. }
  68. }
  69. if(this.carSpawner != null){
  70. this.carSpawner.StartSpawner();
  71. }
  72. }
  73. /// <summary>
  74. /// Each car, used from this preset will be despawned, if set the carspawner will be stopped
  75. /// </summary>
  76. private void DespawnCars(){
  77. Debug.Log("despawnCars");
  78. this.activeCars.ForEach(car => this.carPool.DespawnCar(car));
  79. this.activeCars.Clear();
  80. if(this.carSpawner != null){
  81. this.carSpawner.StopSpawner();
  82. }
  83. }
  84. }
  85. }