@Googoogoogoose
Geek brained

Как исправить ошибку Array index out of range?

Ошибка возникла на строках 27 и 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;
	}
}
  • Вопрос задан
  • 1487 просмотров
Решения вопроса 1
@tex0
Посмотрите как у вас инициализирован двумерный массив.
gridHeight - это у вас первая размерность
gridWidth - это вторая

А теперь взгляните на циклы обхода массива. Вы первую размерность обходите по максимальному значению второй.
Т.е - вы бежите по 1-й размерности массива, состоящей из максимум 10-и элементов, счетчиком 2-й размерности, где максимальное кол-во элементов 20. Естественно у вас на 11-м индексе вылетает исключение OutOfRange.

В UpdateGrid у grid[x,y] меняйте местами переменные в индексаторе. (grid[y,x])
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы