我有一个相当简单的问题(可能)如何计算具有给定值的列表中的值?例如,我有一个非常大的列表,我想读取包含某个变量数量的行。
print(dots[i]);
其中dots 是一个列表其中i 是行号。
Unity 给出了一个非严重错误:
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
参数名称:索引
从中,我意识到列表中没有这样的行,但我通过调试检查了它 - 值是 64,它在列表中。谢谢你。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlanetTerrain : MonoBehaviour
{
public static int seed;
public static Color color;
public static bool deathGas = false;
public static float amplitude;
public static float freq;
public int dotcount = 0;
public List<Vector2> chunkdots;
public GameObject tile;
public int worldSize;
private void Awake()
{
seed = Random.Range(1, 10000);
amplitude = Random.Range(8, 100);
freq = Random.Range(83, 100);
Cursor.lockState = CursorLockMode.Locked;
}
private void Start()
{
SetPoints();
StartCoroutine(Generate());
}
void SetPoints()
{
for (int x = 0; x < worldSize; x++)
{
for (int z = 0; z < worldSize; z++)
{
dotcount++;
Debug.Log(dotcount);
chunkdots.Add(new Vector2(x * 16, z * 16));
}
}
}
IEnumerator Generate()
{
yield return new WaitForSeconds(0.1f);
for (int i = 0; i < dotcount; i++)
{
int ic = 0;
ic = dotcount;
Debug.Log("ic = " + ic);
Instantiate(tile, new Vector3(chunkdots[ic].x, 0, chunkdots[ic].y), Quaternion.identity);
}
}
}
在整个循环中,您为 ic 分配数组的值,从而获得
Index was out of range. 64 个元素的数组中的最后一个索引是 63!而且您不需要将列表的体积视为单独的变量,List 具有 Count 属性,就像常规的 Lenght 数组一样。
如果列表中有 64 个项目,请确保您没有尝试获取索引 64 处的项目。列表中的第 64 个项目将位于索引 63,因为索引从 0 开始,而不是 1。