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

如何解决如何修复在最近的航路点巡逻 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);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?