如何修复在最近的航路点巡逻 ai 上发生的参数超出范围异常

问题描述

您好,我是 c# 和 unity 的新手,任何人都知道如何修复我正在处理的这段代码中发生的参数超出范围异常。此代码用于查找最近的航路点 AI,我尝试更改整数但无济于事。感谢您花时间阅读本文。

public class FindClosest : MonoBehavIoUr

{

public GameObject[] waypoints;
Animator anim;
public float rotspeed = 0.8f;
public float speed = 3f;
float accuracyWP = 2.0f;
int currentWP = 0;

List<Transform> path = new List<Transform>();
void Start()
{
    anim = GetComponent<Animator>();
    foreach (GameObject go in waypoints)
    {
        path.Add(go.transform);
    }
    currentWP = FindClosestWP();
    anim.SetBool("isWalking",true);
}

int FindClosestWP()
{
    if (path.Count == 0) return -1;
    int closest = 0;
    float lastdist = Vector3.distance(this.transform.position,path[0].position);
    for(int i = 1; i < path.Count; i++)
    {
        float thisdist = Vector3.distance(this.transform.position,path[i].position);
        if(lastdist > thisdist && i != currentWP)
        {
            closest = i;
        }
    }
    return closest;
}
void Update()
{
    Vector3 direction = path[currentWP].position - transform.position;
    this.transform.rotation = Quaternion.Slerp(transform.rotation,Quaternion.LookRotation(direction),rotspeed * Time.deltaTime);
    this.transform.Translate(0,Time.deltaTime * speed);
    if(direction.magnitude < accuracyWP)
    {
        path.Remove(path[currentWP]);
        currentWP = FindClosestWP();
    }
}

} This is the error

解决方法

我看不到错误来自哪一行,但在更新中使用了 currentWP 变量,而没有检查它是否为有效值(或路径变量是否有效)。我建议至少为此添加一个检查更新,例如:

if (path != null && currentWP >= 0 && currentWP < path.Count)
{
    // existing Update logic goes here
}

如果这不能解决问题,则从中获取错误日志的完整副本。它将指示文件中的行号,这将有助于缩小范围。

我不认为这会导致问题,但值得注意的是,在 FindClosestWP 中,它似乎总是跳过列表中的第一个航点?索引从 1 而不是 0 开始,这是故意的吗?那里的 lastDist 计算似乎也总是参考第一点而不是最近的点(即 currentWP)。我认为这一行:

float lastDist = Vector3.Distance(this.transform.position,path[0].position);

可能需要

float lastDist = Vector3.Distance(this.transform.position,path[currentWP].position);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...