【问题标题】:How can I get form a GameObject a list of components attached to it?如何从 GameObject 中获取附加到它的组件列表?
【发布时间】:2018-10-29 00:15:17
【问题描述】:

附加组件我的意思是每个组件的名称。

var list = gameObj.GetComponents(typeof(Component));
                if (!componentsList.Contains(gameObj.name))
                    componentsList.Add(gameObj.name);
                for (int i = 0; i < list.Length; i++)
                {
                    if (!componentsList.Contains(list[i].name))
                        componentsList.Add(list[i].name);
                }

此代码仅使用 GameObjects 创建一个列表。 但我想要一个这种格式的列表,例如:

立方体1 网格渲染器 盒子对撞机 领域 网格渲染器 盒子对撞机

最后是一个包含每个对象名称及其组件的列表。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    我假设当您说您需要组件的名称时,您实际上是指类型。 Component.name 实际上返回 Component 附加到的 GameObject 的名称,因此它对于所有组件都是相同的。

    您可以执行以下操作

        foreach(var component in GetComponents()) {
            Debug.Log(component.GetType());
        }
    

    我想知道你需要它来做什么......

    【讨论】:

      【解决方案2】:
      Component[] comps=gameObj.GetComponents();
      
      List<Component> complist= new List<Component>();
      
      for(inti =0;i<comps.length;i++){
      complist.Add(comps[i]);
      }
      

      【讨论】:

      • 虽然这段代码可能会回答这个问题,但最好在不介绍其他代码的情况下解释它是如何解决问题的,以及为什么要使用它。从长远来看,纯代码的答案没有用处。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-30
      • 2019-02-26
      • 1970-01-01
      • 2019-11-27
      • 2022-01-21
      相关资源
      最近更新 更多