Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Need help with array problem

Discussion in '2D' started by TheWebExpert, Oct 2, 2019.

  1. TheWebExpert

    TheWebExpert

    Joined:
    Apr 14, 2015
    Posts:
    198
    Code (CSharp):
    1.   public GameObject[] Dig = new GameObject[10];
    2.   ...
    3.   j = 1;
    4.   for (i = 0; i < j; i++)
    5.     {
    6.       GameObject go = First_Digit0;
    7.       if (i == 0) go = Instantiate(Digit0, new Vector3(XStart + k, YStart, 1), Quaternion.identity) as GameObject;
    8.       if (i == 1) go = Instantiate(Digit1, new Vector3(XStart + k, YStart, 1), Quaternion.identity) as GameObject;
    9.       if (i == 2) go = Instantiate(Digit2, new Vector3(XStart + k, YStart, 1), Quaternion.identity) as GameObject;
    10.       if (i == 3) go = Instantiate(Digit3, new Vector3(XStart + k, YStart, 1), Quaternion.identity) as GameObject;
    11. >>    Dig[i] = go;  <<
    12.       ...
    13.  
    I'm getting an "Index was outside the bounds of the array" error on the line indicated. How do I fix this??
     
  2. Luto_Akino

    Luto_Akino

    Joined:
    Feb 20, 2018
    Posts:
    21
    The length of your "Dig" variable is not updated in the Unit Editor, check that the length[10] is correct. Otherwise, update it manually or choose the reset option found in the small gear icon of your script component.

    (the incorrect declaration of your variables "j" and "i" are intentional? check that too, and I guess you have declared Digit0 Digit1 Digit2 Digit3)
     
  3. TheWebExpert

    TheWebExpert

    Joined:
    Apr 14, 2015
    Posts:
    198
    ...
    uh.
    I changed the line "int i, j, k = 0;" to "int i = 0, j = 0, k = 0;" ... and everything worked. I don't know why setting these to zero makes any difference. But it works, and that's what counts.
     
    Luto_Akino likes this.