我试图通过循环x次或直接添加x nr个元素来添加元素的非恒定值。
我尝试循环x次,并在每次迭代中添加一个元素,但最终只包含一个元素。我也尝试过添加一个集合,但是发生了相同的结果。
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class tileMapDepth
{
public List<bool> tileMapWidth;
public tileMapDepth(List<bool> realWidth)
{
this.tileMapWidth = realWidth;
}
}
public class TestListTypeAndSuch : MonoBehaviour
{
public List<tileMapDepth> tileMap = new List<tileMapDepth>(1);
public int width = 5;
public int depth = 5;
void Start()
{
for (int i = 0; i < depth; i++)
{
tileMap.Add(new tileMapDepth(new List<bool>(new List<bool>(width))));
foreach (tileMapDepth tile in tileMap)
{
for (int j = 0; j < width; j++)
{
tile.tileMapWidth.Add(false);
}
}
}
}
}
预期结果是将nr个元素添加到列表中,而不仅仅是一个元素。 当我尝试添加具有恒定值的布尔值作为量时,它可以正常工作。但是我需要添加一个动态变量。下面的代码是唯一起作用的代码。
for (int i = 0; i < depth; i++)
{
tileMap.Add(new tileMapDepth(new List<bool>(new List<bool>(new bool[13]))));
}
答案 0 :(得分:2)
尝试
List<T>.AddRange(IEnumerable<T>) Method
将指定集合的元素添加到列表的末尾。
答案 1 :(得分:0)
您正尝试将false
的值添加到列表中5次,即在tileMapWidth
中。要向列表中添加相同的值n次,可以使用Enumerable.Repeat()
List<bool> tileMapWidth = Enumerable.Repeat(false, 5).ToList();
您可以将此列表作为参数传递给tileMapDepth()
类
类似
tileMap.Add(new tileMapDepth(tileMapWidth));