【问题标题】:(Unity) How to get generic component class from GameObject?(Unity) 如何从 GameObject 中获取通用组件类?
【发布时间】:2020-05-11 17:24:05
【问题描述】:

如何在 Unity 中从生成的 GameObject 中获取通用组件?

即我有一个基本的泛型类:

class Base<T> : MonoBehaviour where T : MonoBehaviour 
{
    public Foo() {}
}

和派生类:

class Example : Base<Example>
{

}

我想知道从生成的 GameObject 中获取这个类,我将它作为一个组件附加。

我试过了,但结果为空,所以我决定寻求帮助:)

// @object - Spawned before and exists.
Base<MonoBehaviour> tmp = @object.GetComponent<Base<MonoBehaviour>>();

【问题讨论】:

    标签: c# unity3d generics gameobject


    【解决方案1】:

    尝试使用接口实现:

    class Base<T> : MonoBehaviour, IBase where T : MonoBehaviour 
    

    并从 GO 获取接口:

    var tmp = @object.GetComponent<IBase>();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 2015-01-25
      • 2023-03-31
      • 2017-10-16
      • 1970-01-01
      • 2019-12-02
      • 2023-02-14
      相关资源
      最近更新 更多