- Home /
can Array resize at runtime?
I'm getting a IndexOutOfRangeException at line 33, by checking with Debug.console on line 18 I've noticed that the length of the array is changed during runtime by starting at 2 (which is the number of prefabs i have in it) and going to 0 once run it, however it doesn't stop the prefabs from being loaded as intended ( random index with random location), it's not causing any issue other than raising the exception, i'm asking this because to my understanding it shouldn't happen with an array, so basically how does unity treat arrays?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManagerX : MonoBehaviour
{
public GameObject[] objectPrefabs;
private float spawnDelay = 2;
private float spawnInterval = 1.5f;
private PlayerControllerX playerControllerScript;
// Start is called before the first frame update
void Start()
{
Debug.Log("size at start" + objectPrefabs.Length); //<-- test
playerControllerScript = GameObject.Find("Player").GetComponent<PlayerControllerX>();
InvokeRepeating("SpawnObjects", spawnDelay, spawnInterval);
}
// Spawn obstacles
void SpawnObjects()
{
// If game is still active, spawn new object
if (!playerControllerScript.gameOver)
{
// Set random spawn location and random object index
Vector3 spawnLocation = new Vector3(30, Random.Range(5, 16), 0);
int index = Random.Range(0, objectPrefabs.Length);
Instantiate(objectPrefabs[index], spawnLocation, objectPrefabs[index].transform.rotation); //<-exception here
}
}
}
Answer by xxmariofer · Dec 02, 2020 at 08:57 AM
Unity doesnt treat arrays differently, arrays cant resize but you can be overriding the array somewhere else (since its public is imposible for us to tell) you could be re-initializing the array or simply destroying it
Answer by Petrusion · Dec 02, 2020 at 12:26 PM
Your OutOfRangeException is probably because Random.Range(min, max) returns values including max, not excluding.
No. Random.Range $$anonymous$$ is inclusive max is exclusive
Your answer
![](https://koobas.hobune.stream/wayback/20220613020807im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
ArrayIsOutOfRange 0 Answers
Problem with arrays and accessing sriptable objects. 2 Answers
Array Out Of Range: Jibe 0 Answers
Index Array is out of Range 1 Answer
Array out of index? 1 Answer