优化代码
时间: 2023-08-11 13:15:52 浏览: 41
以下是代码的优化版本:
```csharp
private GameObject SelectTarget()
{
GameObject temp = null;
float minDistance = Mathf.Infinity; // 用 Mathf.Infinity 初始化最小距离
// 使用 foreach 遍历敌人列表
foreach (GameObject enemyObject in enemy)
{
// 计算当前敌人与塔的距离
float distance = Vector3.Distance(transform.position, enemyObject.transform.position);
// 如果距离小于等于攻击范围并且距离小于当前最小距离,更新最小距离和目标敌人
if (distance <= dis && distance < minDistance)
{
minDistance = distance;
temp = enemyObject;
}
}
return temp;
}
```
这个版本使用了 foreach 循环来遍历敌人列表,用 Mathf.Infinity 来初始化最小距离,避免了在计算距离时出现的错误。同时,将计算距离和更新最小距离和目标敌人的操作放在了同一个 if 语句中,使代码更加简洁。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)