如何解决如何修复在最近的航路点巡逻 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();
}
}
解决方法
我看不到错误来自哪一行,但在更新中使用了 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 举报,一经查实,本站将立刻删除。