You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.5 KiB

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
namespace BuildSystem
{
public class CarController : MonoSingleton<CarController>
{
[Header("车辆生成位置")]
public List<Vector2Int> birth = new List<Vector2Int>();
[Header("车辆预制体")]
public Car[] carPrefabs;
[Header("生成最大车辆数")]
public int carNumber;
[NonSerialized]
public int number = 0;
[Header("车辆创建时间")]
public Vector2 createTime;
[Header("40为标准速度")]
public Vector2 speed;
public List<Car> allCar = new List<Car>();
void Start()
{
birth.Add(new Vector2Int(0 , 2));
birth.Add(new Vector2Int(10, 0));
birth.Add(new Vector2Int(13, 5));
}
/// <summary>
/// 开启创建车辆协程
/// </summary>
public void StartCreateCar() {
StartCoroutine(CreateCar());
StartCoroutine(ReduceCar());
}
/// <summary>
/// 创建车辆
/// </summary>
/// <returns></returns>
IEnumerator CreateCar() {
while (true) {
yield return new WaitUntil(() => { return number < carNumber; });
yield return new WaitForSeconds(UnityEngine.Random.Range(createTime.x, createTime.y));
number++;
GameObject car = Instantiate(carPrefabs[UnityEngine.Random.Range(0, carPrefabs.Length)].gameObject,transform);
car.GetComponent<Car>().OpenMove(birth[UnityEngine.Random.Range(0, birth.Count)], UnityEngine.Random.Range(speed.x,speed.y));
allCar.Add(car.GetComponent<Car>());
}
}
/// <summary>
/// 删减车辆协程
/// </summary>
/// <returns></returns>
IEnumerator ReduceCar()
{
while (true)
{
yield return new WaitUntil(() => { return number > carNumber; });
yield return new WaitForSeconds(UnityEngine.Random.Range(createTime.x, createTime.y));
number--;
int id = UnityEngine.Random.Range(0, allCar.Count - 1);
Car car = allCar[id];
allCar.RemoveAt(id);
Destroy(car.gameObject);
}
}
public void CarNumberChange(float num) {
carNumber = (int)(num * 70) + 30;
}
}
}