[英]Unity3d scripting error c# IndexOutOfRangeException: Array index is out of range
This is my spawning script belowwritten in c# The script should create objects randomly in the scene. 这是用c#编写的我的生成脚本。该脚本应在场景中随机创建对象。
The issue is that I'm getting this error at runtime. 问题是我在运行时遇到此错误。
IndexOutOfRangeException: Array index is out of range.
CreateEasterEggs.MakeThingToSpawn () (at Assets/CreateEasterEggs.cs:52)
CreateEasterEggs.Update () (at Assets/CreateEasterEggs.cs:28)
Not sure what I have done wrong, thinking its something to do with the game object? 不确定我做错了什么,认为与游戏对象有关吗?
Thank you. 谢谢。
using UnityEngine;
using System.Collections;
public class CreateEasterEggs : MonoBehaviour
{
public float secondsBetweenSpawning = 0.1f;
public float xMinRange = -25.0f;
public float xMaxRange = 25.0f;
public float yMinRange = -5.0f;
public float yMaxRange = 0.0f;
public float zMinRange = -25.0f;
public float zMaxRange = 25.0f;
public GameObject[] spawnObjects; // what prefabs to spawn
private float nextSpawnTime;
void Start ()
{
// determine when to spawn the next object
nextSpawnTime = Time.time+secondsBetweenSpawning;
}
void Update ()
{
// if time to spawn a new game object
if (Time.time >= nextSpawnTime) {
// Spawn the game object through function below
MakeThingToSpawn ();
// determine the next time to spawn the object
nextSpawnTime = Time.time+secondsBetweenSpawning;
}
}
void MakeThingToSpawn ()
{
//Start the vector at an invalid position
Vector3 spawnPosition = new Vector3(0, 0, 0);
//while we are not in the right range, continually regenerate the position
while ((spawnPosition.z < 4 && spawnPosition.z > -4) || (spawnPosition.x < 4 && spawnPosition.x > -4))
{
spawnPosition.x = Random.Range (xMinRange, xMaxRange);
spawnPosition.y = Random.Range (yMinRange, yMaxRange);
spawnPosition.z = Random.Range (zMinRange, zMaxRange);
}
// determine which object to spawn
int objectToSpawn = Random.Range (0, spawnObjects.Length);
// actually spawn the game object
GameObject spawnedObject = Instantiate (spawnObjects [objectToSpawn], spawnPosition, transform.rotation) as GameObject;
// make the parent the spawner so hierarchy doesn't get super messy
spawnedObject.transform.parent = gameObject.transform;
}
}
IndexOutOfRange
means that you tried to access to an element of an array that doesn't exist. IndexOutOfRange
表示您尝试访问不存在的数组元素。
In your case as you are doing it with Random.Range (0, spawnObjects.Length);
在您的情况下,使用Random.Range (0, spawnObjects.Length);
Then the only possible case is that your array is empty. 那么唯一可能的情况是您的数组为空。
Try to Debug.Log(spawnObjects.Length):
before the Instantiate
and you will see that in fact your array of gameobjects is empty as It will return 0. 尝试Debug.Log(spawnObjects.Length):
在Instantiate
之前,您会发现实际上您的游戏对象数组为空,因为它将返回0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.