【问题标题】:Getting an error on my NavAgent script in Unity. IndexOutOfRangeException: Array index is out of range在 Unity 中我的 NavAgent 脚本出现错误。 IndexOutOfRangeException:数组索引超出范围
【发布时间】:2015-01-12 12:47:54
【问题描述】:

我收到一个错误“IndexOutOfRangeException: Array index is out of range. 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 ();
}
}

【问题讨论】:

  • 你没有初始化myPathAgent

标签: c# arrays indexing unity3d


【解决方案1】:
Vector3 newTravelPosition = myPathNodes [navIndex].transform.position;

异常可能发生在这一行。您应该初始化 myPathNodes。 myPathNodes[navIndex]上不会有任何内容

[SerializeField]
PathNode[] myPathNodes; //this will be null.

【讨论】:

    【解决方案2】:

    您需要考虑您的代码并提出一个问题。开始游戏前你知道数组的最大大小吗?

    如果答案是肯定的,则需要像这样初始化数组:

    PathNode[] myPathNodes = new  PathNode[maximumSize];
    

    否则,我建议您使用列表而不是数组(因为列表大小是动态分配的),您可以在此处阅读有关 C# 中列表的更多信息:

    http://www.dotnetperls.com/list

    如果您需要更多帮助,请随时发表评论 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      相关资源
      最近更新 更多