I have an array of GameObjects called characterList.
I want to set a playerpref to the name of an object in this gameobject array but it continuously gives me an error on this line
characterName = CharacterList[playerId].name;
I have set the playerId parameter when the button is clicked to 0
Have no clue about why this is happening…
Code below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class CharacterChoose : MonoBehaviour
{
public GameObject[] characterList;
private int index;
public string characterName;
// Use this for initialization
private void Start()
{
index = PlayerPrefs.GetInt("CharacterSelected");
characterList = new GameObject[transform.childCount];
//fill with models
for (int i = 0; i < transform.childCount; i++)
{
characterList[i] = transform.GetChild(i).gameObject;
}
//toggle them off
/* foreach (GameObject go in characterList)
go.SetActive(false);
*/
}
public void onClick(int playerId)
{
index = playerId;
PlayerPrefs.SetInt("CharacterSelected", index);
characterName = characterList[index].name;
PlayerPrefs.SetString("CharacterName", characterName);
SceneManager.LoadScene("Worlds");
}
}
If playerId is zero and you are still getting an out of bounds error, that implies there are no items in the list. Indices start counting from zero.
Have you checked whether line 23 is adding items - i.e. is transform.childCount on line 18 returning zero (meaning there is no element with index [0])?
So i put some debug logs, and I put one at the end of the code in side the start method and it printed out 13, however when i put it inside the click method it said 0
First, make all your member variables private. That way, they can only be updated from within that script. Next, is to find out all the places in the script that write to characterList. One of them must be clearing it.
This is an old post, but I’m incredibly grateful for it. I’ve been so confused why all of my rotated 3d floor tiles will instantiate except one prefab in the array. Turns out I have the same script on that prefab with an empty array. You rock!