0

I'm still learning about Unity and trying to create some simple games.. but i got a same error for a few days when i tried to fill array from public function.. it said that my index was outside the bounds of array..

is there anything related with public or not? i do know about the cause of this error. what iam asking is why it gives different value from different function(same script)? please help :d (sorry for my bad english)

this is my code :

public void PencetTombol()
{
    //this is where i got error line
    prefab[0].GetComponentInChildren<Text>().text = "test";
}
void cekkata()
{
    //this code works 
    prefab[0].GetComponentInChildren<Text>().text = "test";
}
void buat_kotak()
{
    pindah = false;
    var test = "CHELSEA";
    prefab = new GameObject[test.Length];
    for (int i = 0; i < test.Length; i++)
    {
        if (test[i] != ' ')
        {
        prefab[i] = Instantiate(prefab2, new Vector3(0.5f, 0.5f, 0.5f), Quaternion.identity);

            if (pindah == false)
            {
                prefab[i].transform.SetParent(panelatas.transform, false);
            }
            else
            {
                prefab[i].transform.SetParent(paneltengah.transform, false);
            }
        }
        else
        {
            pindah = true;
        }
    }
}
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
welly
  • 1
  • 3

1 Answers1

0

Your error has no connection with access modifiers.

This error is thrown when you try to access an array element that does not yet exist.

Example:

string[] test = { "test" };

var x = test[0]; --> success
var y = test[1]; --> out of bounds
Guilherme Martin
  • 837
  • 1
  • 11
  • 22
  • Only explains the *why*, but not the actual *solution*. – MakePeaceGreatAgain Oct 22 '19 at 11:23
  • well i do know about the error.. what exactly i need is.. "why i can access it through different function?" is there anything related with public function or not?in function cekkata(), it works flawlessly.. meanwhile i can't access it in function pencettombol().. – welly Oct 22 '19 at 11:28