CarSpawner.cs 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class CarSpawner : MonoBehaviour
  5. {
  6. public List<GameObject> Spawners;
  7. public List<GameObject> Cars;
  8. public float SpawnRate;
  9. private List<float> lastSpawn = new List<float>();
  10. // Start is called before the first frame update
  11. void Start()
  12. {
  13. Debug.Log("Start");
  14. for (int i = 0; i <= Spawners.Count; i++)
  15. {
  16. lastSpawn.Add(Time.time);
  17. }
  18. }
  19. // Update is called once per frame
  20. void Update()
  21. {
  22. int index = 0;
  23. foreach(GameObject spawn in Spawners){
  24. SpawnCar(spawn, index);
  25. index++;
  26. }
  27. }
  28. private void SpawnCar(GameObject spawn, int index)
  29. {
  30. if(lastSpawn[index] + SpawnRate > Time.time)
  31. {
  32. // No need for a new spawn
  33. return;
  34. }
  35. Debug.Log("Spawn!");
  36. int carIndex = Random.Range(0, Cars.Count);
  37. GameObject car = Cars[carIndex];
  38. GameObject newCar = Object.Instantiate(car, spawn.transform.position,spawn.transform.rotation);
  39. lastSpawn[index] = Time.time;
  40. }
  41. }