【问题标题】:How do I retrieve data from a child object in a base object array?如何从基础对象数组中的子对象检索数据?
【发布时间】:2020-08-16 14:10:39
【问题描述】:

假设我有一个 GameObject 数组,其中包含子对象:

GameObjects = new List<GameObject>
        {
            new Tile(0, 0, new int[] { 1, 2, 3, 0 }),
            new BuyTile(1, 0),
            new BuyTile(0, 1),
            new BuyTile(-1, 0),
            new BuyTile(0, -1)
        };

我想访问这个数组中 Tile 对象的属性。

public void UpdateResources()
    {
        for (int i = 0; i < GameObjects.Count; i++)
        {
            if (GameObjects[i] is Tile)
            {
                /* I want to read a property of the Tile here, and it's not in the abstract class 
                 * GameObject.
                */
            }
        }
    }

我该怎么做? 我自己找不到关于这个问题的任何信息,但如果有人有另一个相关问题的链接,我会很乐意接受。

【问题讨论】:

    标签: c# arraylist


    【解决方案1】:
    
    public void UpdateResources()
        {
            for (int i = 0; i < GameObjects.Count; i++)
            {
                if (GameObjects[i] is Tile t)
                {
                     t.X // <- read property
                    
                }
            }
        }
    

    【讨论】:

      【解决方案2】:

      您可以使用as 运算符和空值检查:

          for (int i = 0; i < GameObjects.Count; i++)
          {
              var tile = GameObjects[i] as Tile;
              if (tile != null)
              {
                  // use tile 
              }
          }
      

      如果你的 unity 版本支持 C# 7.0,你可以使用 is operator with the type pattern:

          for (int i = 0; i < GameObjects.Count; i++)
          {
              if (GameObjects[i] is Tile tile)
              {
                  // use tile
              }
          }
      

      【讨论】:

        【解决方案3】:

        你可以试试Linq

        public void UpdateResources() {
          foreach (Tile tile in GameObjects.OfType<Tile>()) {
            //TODO: put relevant code here, e.g.
            // tile.SomeProperty = tile.SomeProperty - 5; 
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2020-01-21
          • 1970-01-01
          • 2016-02-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-06-17
          相关资源
          最近更新 更多