Answer the question
In order to leave comments, you need to log in
How to fix Array index out of range error?
The error occurred on lines 27 and 59.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Game : MonoBehaviour
{
public static int gridWidth = 10;
public static int gridHeight = 20;
public Transform[,] grid = new Transform[gridHeight, gridWidth];
void Start ()
{
SpawnNextFigure();
}
void Update ()
{
}
public void UpdateGrid (Tetromino figure)
{
for (int y = 0; y < gridHeight; ++y)
{
for (int x = 0; x < gridWidth; ++x)
{
if (grid[x, y] != null) // здесь возникла ошибка
{
if (grid[x,y].parent == figure.transform)
{
grid[x, y] = null;
}
}
}
}
foreach (Transform fig in figure.transform)
{
Vector2 pos = Round (fig.position);
if (pos.y < gridHeight)
{
grid[(int)pos.x, (int)pos.y] = fig;
}
}
}
public Transform GetTransformAtGridPosition (Vector2 pos)
{
if (pos.y > gridHeight -1)
{
return null;
} else
{
return grid[(int)pos.x, (int)pos.y]; // здесь возникла ошибка
}
}
public void SpawnNextFigure ()
{
GameObject nextFigure = (GameObject)Instantiate(Resources.Load(GetRandomFigure(), typeof(GameObject)), new Vector3(5.0f, 20,0f), Quaternion.identity);
}
public bool CheckIsInsideGrid (Vector2 pos)
{
return ((int)pos.x >= 0 && (int)pos.x < gridWidth && (int)pos.y >=0 && pos.y <gridHeight);
}
public Vector2 Round (Vector2 pos)
{
return new Vector2 (Mathf.Round(pos.x), Mathf.Round(pos.y));
}
string GetRandomFigure ()
{
int RandomFigure = Random.Range(1,8);
string RandomFigureName = "Prefabs/Tetromino_CornerLeft";
switch (RandomFigure)
{
case 1:
RandomFigureName = "Prefabs/Tetromino_Triangle";
break;
case 2:
RandomFigureName = "Prefabs/Tetromino_CornerLeft";
break;
case 3:
RandomFigureName = "Prefabs/Tetromino_CornerRight";
break;
case 4:
RandomFigureName = "Prefabs/Tetromino_Cube";
break;
case 5:
RandomFigureName = "Prefabs/Tetromino_Line";
break;
case 6:
RandomFigureName = "Prefabs/Tetromino_ZigzagLeft";
break;
case 7:
RandomFigureName = "Prefabs/Tetromino_ZigzagRight";
break;
}
return RandomFigureName;
}
}
Answer the question
In order to leave comments, you need to log in
Look at how you initialized a two-dimensional array.
gridHeight is your first dimension
gridWidth is your second
Now take a look at the array traversal loops. You bypass the first dimension on the maximum value of the second.
That is, you run along the 1st dimension of the array, consisting of a maximum of 10 elements, with a counter of the 2nd dimension, where the maximum number of elements is 20. Naturally, an OutOfRange exception occurs at the 11th index.
In UpdateGrid, have grid[x,y] swap the variables in the indexer. (grid[y,x])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question