CarPool.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. namespace TrafficSimulation{
  5. public class CarPool : MonoBehaviour
  6. {
  7. public TrafficSystem trafficSystem;
  8. public static CarPool SharedInstance;
  9. public List<GameObject> carModels;
  10. public List<GameObject> pooledCars;
  11. public int poolSize;
  12. void Awake() {
  13. SharedInstance = this;
  14. pooledCars = new List<GameObject>();
  15. GameObject tmpInstance;
  16. for(int i = 0; i < poolSize; i++){
  17. tmpInstance = Instantiate(carModels[Random.Range (0, carModels.Count)]);
  18. VehicleAI vAI = tmpInstance.GetComponent<VehicleAI>();
  19. if(vAI == null){
  20. Debug.Log("Carmodel has no AI. Destorying Instance!");
  21. Destroy(tmpInstance);
  22. continue;
  23. }
  24. vAI.trafficSystem = this.trafficSystem;
  25. CarSitter carSitter = tmpInstance.GetComponent<CarSitter>();
  26. if(carSitter != null){
  27. carSitter.carPool = this;
  28. }
  29. tmpInstance.SetActive(false);
  30. pooledCars.Add(tmpInstance);
  31. }
  32. }
  33. public GameObject GetCar(){
  34. foreach(GameObject car in pooledCars){
  35. if(!car.activeInHierarchy){
  36. return car;
  37. }
  38. }
  39. Debug.Log("no car free to use. returning null!");
  40. return null;
  41. }
  42. public GameObject SpawnCar(Transform spawnTranform){
  43. return SpawnCar(spawnTranform.position, spawnTranform.rotation, null);
  44. }
  45. public GameObject SpawnCar(Vector3 spawnPos, Quaternion spawnRot, Transform lookAt)
  46. {
  47. GameObject car = this.GetCar();
  48. if (car == null)
  49. {
  50. Debug.Log("No car was available. Spawn aborted");
  51. return null;
  52. }
  53. car.transform.position = spawnPos;
  54. car.transform.rotation = spawnRot;
  55. if(lookAt != null)
  56. {
  57. car.transform.LookAt(lookAt);
  58. }
  59. VehicleAI ai = car.GetComponent<VehicleAI>();
  60. ai.vehicleStatus = Status.GO;
  61. car.SetActive(true);
  62. return car;
  63. }
  64. public void DespawnCar(GameObject car){
  65. car.SetActive(false);
  66. }
  67. }
  68. }