【问题标题】:Getting GameObject Component获取游戏对象组件
【发布时间】:2020-09-03 00:50:18
【问题描述】:

我正在使用它在 GameObject 中查找一些脚本:

GameObject.Find("GameView").GetComponent<SomeClass>();

我是 Unity 新手,想看看以下是否可行:

SomeClass View1;
SomeClass View2;
View2 = GameObject.Find("GameView").GetComponent<View1.GetType()>();

当然会引发错误。但是是否可以为GetComponent动态分配类定义?

【问题讨论】:

  • @Pluto 不,它不会。 public bool TryGetComponent(Type type, out Component component); 会。泛型类型参数总是必须是编译时常量

标签: unity3d


【解决方案1】:

是和不是

不使用通用版本,而是使用GetComponent(Type)

var view2 = GameObject.Find("GameView").GetComponent(View1.GetType);

您至少获得了 Component 的引用,但问题是您很可能仍需要将其转换为更有用的东西才能执行任何方法或访问其上的字段。

Component 除外,当然适合您的用例。

否则,如果您已经知道您的组件将共享某个基类或接口,您可以改用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2011-04-26
    • 2020-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多