- Home /
Index out of bound when trying to select a character
I am having a small error here while trying to access a car in the character selection script I did whatever i could but could not solve it can anyone please help me using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement;
public class CarSelector : MonoBehaviour { //Made gameobject of the character list private GameObject[] characterList; private int index;
private void Start()
{
index = PlayerPrefs.GetInt("Character Selection");
//added count to the child objects of the character list
characterList = new GameObject[transform.childCount];
//got the first character in the list
for (int i = 0; i < transform.childCount; i++)
{
characterList[i] = transform.GetChild(i).gameObject;
}
//disabled the inactive child characters
foreach(GameObject go in characterList)
go.SetActive(false);
//toggle on the first character
if (characterList[index])
characterList[index].SetActive(true);
}
Answer by sacredgeometry · Nov 29, 2020 at 04:09 AM
What you have is an off by one error:
https://en.wikipedia.org/wiki/Off-by-one_error
Basically you are trying access something outside of the bounds of your array. i.e. Say your array is 5 items long and you do myArray[5]
, essentially asking for the 6th item in it. You will get that error.
I hope that makes it pretty obvious which two lines of code are probably causing the problem.
Thanks for replying man there are two lines causing this error if (characterList[index]) characterList[index].SetActive(true); so should I set some kind of value to the index in order to make it work?
Your answer
Follow this Question
Related Questions
What means this error ? 1 Answer
IndexOutOfRangeException: Array index is out of range. 0 Answers
Array index is out of range error Edited 1 Answer
IndexOutOfRangeException 1 Answer