12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- namespace TrafficSimulation{
- public class CarPool : MonoBehaviour
- {
- public TrafficSystem trafficSystem;
- public static CarPool SharedInstance;
- public List<GameObject> carModels;
- public List<GameObject> pooledCars;
- public int poolSize;
- void Awake() {
- SharedInstance = this;
- pooledCars = new List<GameObject>();
- GameObject tmpInstance;
- for(int i = 0; i < poolSize; i++){
- tmpInstance = Instantiate(carModels[Random.Range (0, carModels.Count)]);
- VehicleAI vAI = tmpInstance.GetComponent<VehicleAI>();
- if(vAI == null){
- Debug.Log("Carmodel has no AI. Destorying Instance!");
- Destroy(tmpInstance);
- continue;
- }
- vAI.trafficSystem = this.trafficSystem;
- CarSitter carSitter = tmpInstance.GetComponent<CarSitter>();
- if(carSitter != null){
- carSitter.carPool = this;
- }
- tmpInstance.SetActive(false);
- pooledCars.Add(tmpInstance);
- }
- }
- public GameObject getCar(){
- foreach(GameObject car in pooledCars){
- if(!car.activeInHierarchy){
- return car;
- }
- }
- Debug.Log("no car free to use. returning null!");
- return null;
- }
- public GameObject SpawnCar(Transform spawnTranform){
- return SpawnCar(spawnTranform.position, spawnTranform.rotation, null);
- }
- public GameObject SpawnCar(Vector3 spawnPos, Quaternion spawnRot, Transform lookAt)
- {
- GameObject car = this.getCar();
- if (car == null)
- {
- Debug.Log("No car was available. Spawn aborted");
- return null;
- }
- car.transform.position = spawnPos;
- car.transform.rotation = spawnRot;
- if(lookAt != null)
- {
- car.transform.LookAt(lookAt);
- }
- car.SetActive(true);
- return car;
- }
- public void despawnCar(GameObject car){
- car.SetActive(false);
- }
- }
- }
|