英文:
ArgumentOutOfRangeException: Index was out of range. In a List<List<GameObject>>
问题
以下是您要翻译的内容:
"I was trying to make a List of different kinds of gathering blocks. But I wanted to make it so that there was only 1 in the inspector and then separate them by category in code. I wanted to do this so the inspector did not get cluttered with different lists.
However, after setting it up, I kept getting an error saying ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List`1[T].set_Item (System.Int32 index, T value) (at <9aad1b3a47484d63ba2b3985692d80e9>:0)
BlockPlacing.Start () (at Assets/m/Scripts/BlockPlacing.cs:16)
My code/inspector list looks like this:
Code:
[SerializeField] private List<GameObject> blocks = new List<GameObject>(64);
private List<List<GameObject>> _mineralsList = new List<List<GameObject>>(4);
void Start()
{
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 4; i++)
{
_mineralsList[j].Insert(i, blocks[i]);
}
}
}
A different way of adding to the _mineralList I saw and tried was _mineralsList[j][i] = blocks[i
. But that also didn't work and gave the same error."
英文:
i was trying to make a List of different kinds of gathering blocks. But i wanted to make it so that there was only 1 in the inspector and then seperate them by category in code. I wanted to do this so the inspector did not get cluttered with different lists.
However after setting it up, i kept getting a error saying ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
> Parameter name: index
System.Collections.Generic.List`1[T].set_Item (System.Int32 index, T value) (at <9aad1b3a47484d63ba2b3985692d80e9>:0)
BlockPlacing.Start () (at Assets/m/Scripts/BlockPlacing.cs:16)
My code/inspector list looks like this:
Code:
[SerializeField] private List<GameObject> blocks = new List<GameObject>(64);
private List<List<GameObject>> _mineralsList = new List<List<GameObject>>(4);
void Start()
{
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 4; i++)
{
_mineralsList[j].Insert(i, blocks[i]);
}
}
}
A different way of adding to the _mineralList i saw and tried was _mineralsList[j][i] = blocks[i]
But that also didn't work and gave the same error.
答案1
得分: 0
尝试使用这段代码:
public void Start()
{
for (int j = 0; j < 4; j++)
{
_mineralsList.Add(new List<GameObject>());
for (int i = 0; i < 4; i++)
{
if (i < blocks.Count) {
_mineralsList[j].Add(blocks[i]);
}
}
}
}
英文:
try to use this code:
public void Start()
{
for (int j = 0; j < 4; j++)
{
_mineralsList.Add(new List<GameObject>());
for (int i = 0; i < 4; i++)
{
if (i < blocks.Count) {
_mineralsList[j].Add(blocks[i]);
}
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论