[英]Unity3d scripting error c# IndexOutOfRangeException: Array index is out of range
[英]Getting an error on my NavAgent script in Unity. IndexOutOfRangeException: Array index is out of range
我收到一个错误“ 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 ();
}
}
Vector3 newTravelPosition = myPathNodes [navIndex].transform.position;
可能在此行发生异常。 您应该初始化myPathNodes。 myPathNodes[navIndex]
上没有任何内容
[SerializeField]
PathNode[] myPathNodes; //this will be null.
您需要考虑您的代码并提出一个问题。 在开始游戏之前,您知道数组的最大大小吗?
如果答案是肯定的,则需要像这样初始化数组:
PathNode[] myPathNodes = new PathNode[maximumSize];
另外,我建议您使用列表而不是数组(因为列表大小是动态分配的),您可以在此处阅读有关C#中列表的更多信息:
http://www.dotnetperls.com/list
如果您需要更多帮助,请随时发表评论:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.