Reputation: 750
I'm using this code to spawn a random object from an array:
using UnityEngine;
using System.Collections;
public class enemySpawner : MonoBehaviour {
public GameObject[] enemies;
int enemyNo;
public float maxPos = 6.9f;
public float delayTimer = 0.75f;
float timer;
void Start () {
timer = delayTimer;
}
void Update () {
timer -= Time.deltaTime;
if (timer <= 0) {
Vector3 enemyPos = new Vector3 (transform.position.x, Random.Range (5.0f, -5.5f), transform.position.z);
//enemyNo = Random.Range (0,8);
enemyNo = Random.Range (0, enemies.Length);
Instantiate (enemies[enemyNo], enemyPos, transform.rotation);
timer = delayTimer;
}
}
}
The problem is I want to do the same thing across different scenes. Each scene has a different amount of objects for the array (set in the inspector), so because they're not all the same I'm getting this error:
IndexOutOfRangeException: Array index is out of range.
Is there any way for me to do this differently? Or should I write a new script for each scene?
Upvotes: 0
Views: 2147
Reputation: 888
You need to get the current length of the array, so you can't get out of the current array range.
enemyNo = Random.Range (0, enemies.Length)
Upvotes: 3