优化下这段代码:if(IsResGenerate && IsEnGenerate) { int rand = Random.Range(0, 4); // 根据随机数选择车辆 if (rand == 0) { GameObject car = Instantiate(BlueCar, transform.position, transform.rotation); CarSp = car.GetComponent<Car>(); CarSp.Path(Index); GM.ResIncrease(true); } else if (rand == 1) { GameObject car = Instantiate(GreyCar, transform.position, transform.rotation); CarSp = car.GetComponent<Car>(); CarSp.Path(Index); GM.ResIncrease(true); } else if (rand == 2) { GameObject car = Instantiate(EnCar, transform.position, transform.rotation); CarSp = car.GetComponent<Car>(); CarSp.Path(Index); GM.EnIncrease(true); } else { GameObject car = Instantiate(RedCar, transform.position, transform.rotation); CarSp = car.GetComponent<Car>(); CarSp.Path(Index); GM.ResIncrease(true); } } else if (IsResGenerate) { int rand = Random.Range(0, 3); // 根据随机数选择车辆 if (rand == 0) { GameObject car = Instantiate(BlueCar, transform.position, transform.rotation); CarSp = car.GetComponent<Car>(); CarSp.Path(Index); GM.ResIncrease(true); } else if (rand == 1) { GameObject car = Instantiate(GreyCar, transform.position, transform.rotation); CarSp = car.GetComponent<Car>(); CarSp.Path(Index); GM.ResIncrease(true); } else { GameObject car = Instantiate(RedCar, transform.position, transform.rotation);
时间: 2024-02-10 08:05:52 浏览: 124
c代码-rand那个
可以将重复的代码提取出来,用一个数组来存储车辆预制体,这样可以避免重复代码,提高代码的可读性和可维护性,优化后的代码如下所示:
```
if(IsResGenerate && IsEnGenerate)
{
int rand = Random.Range(0, 4);
// 根据随机数选择车辆
GameObject[] cars = {BlueCar, GreyCar, EnCar, RedCar};
GameObject car = Instantiate(cars[rand], transform.position, transform.rotation);
CarSp = car.GetComponent<Car>();
CarSp.Path(Index);
if(rand == 2)
{
GM.EnIncrease(true);
}
else
{
GM.ResIncrease(true);
}
}
else if (IsResGenerate)
{
int rand = Random.Range(0, 3);
// 根据随机数选择车辆
GameObject[] cars = {BlueCar, GreyCar, RedCar};
GameObject car = Instantiate(cars[rand], transform.position, transform.rotation);
CarSp = car.GetComponent<Car>();
CarSp.Path(Index);
GM.ResIncrease(true);
}
```
阅读全文