Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Feedback Index was outside the bounds of the array help

Discussion in '2D' started by JackAshwell, Nov 9, 2019 at 12:11 PM.

  1. JackAshwell

    JackAshwell

    Joined:
    Oct 21, 2019
    Posts:
    16
    So this is my current code:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Gameboard : MonoBehaviour
    6. {
    7.     private static int boardWidth = 17;
    8.     private static int boardHeight = 17;
    9.    
    10.     public GameObject[,] board = new GameObject[boardWidth, boardHeight]; // stores x and y of each node in relation to board size
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.         Object[] objects = GameObject.FindObjectsOfType(typeof(GameObject)); // finds all nodes and stores in an array
    15.        
    16.         foreach (GameObject o in objects) { // loops for each node
    17.             Vector3 pos = o.transform.position; // finds position of each node
    18.  
    19.             if (o.name != "Pacman") { // checks that they aren't nodes
    20.                 board [(int)pos.x, (int)pos.y] = o; // stores x and y position of each node that isn't pacman in board array
    21.             }
    22.             else {
    23.                 Debug.Log ("Found Pacman at: " + pos);
    24.             }
    25.         }
    26.     }
    27.  
    28.     // Update is called once per frame
    29.     void Update()
    30.     {
    31.        
    32.     }
    33. }
    But when i try to run unity, i get this error:

    IndexOutOfRangeException: Index was outside the bounds of the array.
    Gameboard.Start () (at Assets/Scripts/Gameboard.cs:20)


    Does anyone know what is wrong?

    Thanks!
     
  2. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    6,173
    Use debug on your position. Make sure, xy are within 0-16 int range.