Question by
DranrebKing · Aug 16, 2018 at 06:55 AM ·
scripting problemarraysgameobjectsgrids
Delete GameObject on a specific Grid Location
I decided to make this 5x5 grid:
public GameObject gridBlock;
public static int width = 5;
public static int height = 5;
private GameObject[,] grid = new GameObject[5, 5];
public GameObject theHandler;
//FUNCTION --- SPAWN
public void SpawnGrid()
{
//Spawn Grid
for (int x=0; x < width; x++)
{
for (int y = 0; y < height; y++)
{
//X Block Grid
Vector3 startPos = theHandler.transform.position;
GameObject gridTile = (GameObject)Instantiate(gridBlock);
gridTile.transform.position = new Vector3(startPos.x + x, startPos.y - y, 0);
}
} // End of Loop
}
Now I wanted to a delete a specific grid block (gameObject) that has the position of (1, -2) on the map. I tried using this:
//UPDATE
void Update()
{
if(Input.GetKeyDown("space"))
{
DestroyBlock( 1, -2);
}
}
//FUNCTION --- DESTROY
public void DestroyBlock(int x, int y)
{
GameObject.Destroy(grid[x,y].gameObject);
}
It gives me a "out of range array" error. Any thoughts on this?
Comment
Answer by Cobra_03 · Aug 17, 2018 at 10:09 PM
Once you make the array, the smallest index is 0, so you would have indices of 0 thru 4. -2 will generate an out of range error.
Your answer
Follow this Question
Related Questions
activate a component in a game object from an array 0 Answers
Child-saving script 1 Answer
How do I track the initial direction of a Non Rigidbody gameobject in 2D? 1 Answer
Custom inspector for items in array 1 Answer
Setting GameObject properties in editor when public script fields are changed 2 Answers