【问题标题】:How do I make a multiple lists from one list?如何从一个列表中创建多个列表?
【发布时间】:2017-03-30 02:49:47
【问题描述】:

我有一个可以分配多个条件的项目列表。它们可以是红色、蓝色、绿色或红色与蓝色、蓝色与绿色、红色与绿色或红色与蓝色与绿色。

我希望能够在运行时创建三个列表。

我从一门我可以填写的课程开始

[System.Serializable]
public class Item
{
    public bool red;
    public bool blue;
    public bool green;
}

列出清单

public List<Item> itemList;

我不知道如何制作 redList、blueList 和 greenList。

我对此很迷茫。我觉得我需要对创建的第一个列表进行 for 循环。然后检查bool是否为真,是否将其添加到新列表中。

new List<Item> redList;

for (int i = 0; i < itemList.Count; i++)
    {
      if( red == true)
       {
            redList.Add();
       }
     }

【问题讨论】:

    标签: list unity3d


    【解决方案1】:

    这可能无法回答问题,但它可以帮助某人(甚至是您)到达这里。

    你应该考虑一下标志:

    [System.Serializable]
    public class Item
    {
        public ColorType colorType;
    }
    [Flags]
    enum ColorType
    {
        Red, Blue, Green
    }
    

    然后你有一个编辑器脚本允许在检查器中进行多项选择:

    [CustomPropertyDrawer(typeof(ColorType))]
    public class IMovementControllerDrawer : PropertyDrawer
    {
        public override void OnGUI(Rect _position, SerializedProperty _property, GUIContent _label)
        {
            _property.intValue = EditorGUI.MaskField(_position, _label, _property.intValue, _property.enumNames);
        }
    }
    

    最后你可以使用 colorType 实例来检查它是什么:

    if ((this.colorType & ColorType.Red) == ColorType.Red) { // It is Red}
    if ((this.colorType & ColorType.Green) == ColorType.Green) { // It is Green}
    if ((this.colorType & ColorType.Blue) == ColorType.Blue) { // It is Blue}
    

    注意 & 不是 &&。这是执行一些位操作。然后,您的对象就可以在 if 语句中运行 0、1、2 或所有路径。

    【讨论】:

      【解决方案2】:

      您的总体想法是正确的。我假设一旦您拥有ItemList,您想从中创建三个彩色列表。这是代码。

      new List<Item> redList;
      
      for (int i = 0; i < itemList.Count; i++)
          {
            if(itemList[i].red)
             {
                  redList.Add(itemList[i]);
             }
      
           if(itemList[i].blue)
             {
                  blueList.Add(itemList[i]);
             }
      
           if(itemList[i].green)
             {
                  greenList.Add(itemList[i]);
             }
          }
      

      最后,blueListredListgreenList 将具有 blueredgreen 属性的所有项目设置为 true。由于元素可以将多种颜色设置为 true,因此会有重叠。

      【讨论】:

      • 谢谢!!这更有意义。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 2018-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多