【问题标题】:Array index out of range?数组索引超出范围?
【发布时间】:2015-04-08 16:43:03
【问题描述】:

我创建了预制件,并以 0, 1 ... 9 命名。

我想用rigidbodycollision 创建一个数字。但是我收到以下异常:

IndexOutOfRangeException:数组索引超出范围。 (包装器 stelemref) 对象:stelemref (object,intptr,object) Spawn_Score.Start () (在 Assets/Spawn_Score.cs:17)

代码:

using UnityEngine;
using System.Collections;

public class Spawn_Score : MonoBehaviour {

  private Vector3 startPosition;
  private Quaternion startRotation;

  public GameObject[] number_object;

  public int position;
  public int count;

  // Use this for initialization
  void Start () {
    for (int i = 0; i < 9; i++) {
        number_object [i] = (GameObject)Resources.Load (i.ToString());
    }
    GenerateScore ();
  }

  // Update is called once per frame
  void Update () {

  }

  void GenerateScore() {
    startRotation = transform.rotation;
    count = PlayerPrefs.GetInt ("PlayerScore").ToString ().Length;
    for (int i = 1; i < count; i++) {
        //int number;
        startPosition = new Vector3 (2f*i, 5.6f, 0);
        //number = (int)PlayerPrefs.GetInt("PlayerScore").ToString()[i];
        Instantiate (number_object[1], startPosition, startRotation);
    }
  }
}

【问题讨论】:

  • 您还没有向我们展示number_object 的初始化位置。 (您已经向我们展示了填充数组的位置,但没有展示您实际初始化变量的位置。)
  • 这就是我所拥有的一切。 number_object 不是在页面顶部初始化的吗?如果我是对的。
  • 不,它在代码的早期声明,但它的默认值是null。所以必须初始化它,否则你会得到一个NullReferenceException。 Unity 的某些神奇部分可能会自动对其进行初始化,但我不知道它如何知道数组的大小。
  • 嗯,10 是我命名为 '0' -> '9' 的预制件数量,所以我不明白我不能简单地手动放入它们,因为这些数量不会改变。 For 循环应该在开始 void 时执行此操作。
  • 我认为你没有抓住重点。除非变量已使用足够大的数组进行初始化,否则您希望该循环如何工作?

标签: c# arrays unity3d


【解决方案1】:

您应该为 public GameObject[] number_object 放置虚拟占位符;在你的编辑器中。你不能在不知道大小的情况下动态生成。您在初始化之前动态尝试填充和 size[] 。它不是一个堆栈,因为你不能即兴地推送和弹出东西。我会放一个虚拟的预制对象(准确地说是 9 个),同一个就可以了。这样你将分配 9 个对象,并且大小将保持一致,并且你可以随时填充 change number_object[i]!

创建一个 dummy_prefab,将 Unity 中的 GameObject 数组的大小设置为 9,然后为每个选择 dummy_prefab 作为相同的值。它们将是占位符,不管是相同还是不同的随机 GameObject 类型!

在 UnityScript 中,我在游戏中做了类似的事情。请注意,这不是在 C# 中,而是在 JS 中。但是对于 LevelPieces 和 LevelPiecesXPosition,我必须提前在编辑器中调整它的大小。在我这样做之前,我遇到了同样的数组错误:

public var LevelPieces: GameObject[];
public var LevelPiecesXPosition: float[];

function Start {

  for (var x:int=0;x < LevelPieces.Length;x++) {
      var temp:GameObject = Instantiate(LevelPieces[x], Vector3(LevelPiecesXPosition[x],0,0), Quaternion.Euler(0,0,0));
  }

}

【讨论】:

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