我收到一个错误“IndexOutOfRangeException:数组索引超出范围。NavAgent.FindDestination()”我是C#的新手,而且我以前没有使用过数组,所以我不太确定我的问题是什么。
如有任何帮助,我们将不胜感激,谢谢!
下面是我的完整脚本:
using UnityEngine;
using System.Collections;
public class NavAgent : MonoBehaviour {
NavMeshAgent myNavAgent;
[SerializeField]
PathNode[] myPathNodes;
int navIndex = 0;
// Use this for initialization
void Start () {
myNavAgent = GetComponent ("NavMeshAgent") as NavMeshAgent;
navIndex = 0;
FindDestination ();
}
// Update is called once per frame
void Update () {
}
void FindDestination()
{
Vector3 newTravelPosition = myPathNodes [navIndex].transform.position;
myNavAgent.SetDestination (newTravelPosition);
}
void OnTriggerEnter()
{
++navIndex;
if (navIndex >= myPathNodes.Length)
navIndex = 0;
FindDestination ();
}
}发布于 2014-11-15 10:01:15
Vector3 newTravelPosition = myPathNodes [navIndex].transform.position;可能异常发生在这一行上。您应该初始化myPathNodes。myPathNodes[navIndex]上什么都不会有
[SerializeField]
PathNode[] myPathNodes; //this will be null.发布于 2014-11-15 21:39:42
你需要考虑你的代码,然后问一个问题。在开始游戏之前,你知道数组的最大大小吗?
如果答案是肯定的,则需要像这样初始化数组:
PathNode[] myPathNodes = new PathNode[maximumSize];另外,我建议你使用列表而不是数组(因为列表大小是动态分配的),你可以在这里阅读更多关于C#中列表的内容:
http://www.dotnetperls.com/list
如果您需要更多帮助,请毫不犹豫地发表意见:)
https://stackoverflow.com/questions/26941660
复制相似问题