Ошибка индекса коллекции. Не могу обратиться к объекту коллекции но индексу
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class grid_ : MonoBehaviour
{
private int width;
private int height;
private float speses;
public List<GameObject> gridobject = new List<GameObject>(48);
public GameObject[] arreypl = new GameObject[48];
private void Start()
{
int n = 0;
foreach(GameObject i in arreypl)
{
gridobject[n] = i;
n++;
}
}
public grid_(int width, int height, float speses)
{
this.height = height;
this.width = width;
this.speses = speses;
for(int x = 0; x < height; x++)
{
for (int y = 0; y < width; y++)
{
int n = Random.Range(0, gridobject.Count);
Debug.Log(gridobject[n]);
GameObject a = gridobject[n];
Instantiate(a, Get_world_position(x, y), Quaternion.identity);
Debug.Log(n);
gridobject.RemoveAt(n);
Debug.Log(n);
}
}
}
private Vector3 Get_world_position(int x, int y)
{
return new Vector3(x, y) * speses;
}
}
Выдаёт ошибку ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index подскажите как исправить.
Ответы (1 шт):
Автор решения: CrazyElf
→ Ссылка
Random.Range согласно описанию возвращает число из указанного диапазона, включая обе границы диапазона. В случае возврата gridobject.Count естественно произойдёт выход за границы допустимого диапазона индексов списка [0, gridobject.Count - 1]. Так что нужно вычесть 1 из правой границы:
int n = Random.Range(0, gridobject.Count - 1);