CarPool.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. car.SetActive(true);
  60. return car;
  61. }
  62. public void despawnCar(GameObject car){
  63. car.SetActive(false);
  64. }
  65. }
  66. }