【问题标题】:How can I use GetComponent<"type">() with a parameter?如何将 GetComponent<"type">() 与参数一起使用?
【发布时间】:2021-12-26 21:39:16
【问题描述】:

我需要编写一个基于参数抓取组件的函数。

我尝试使用字符串,然后是 GetType,但它不起作用。

我尝试使用 MonoBehaviour,但没有成功。我当前的版本如下。我错过了什么?

void move(MonoBehaviour co){
            Touch screentouch = Input.GetTouch(0);
            Ray ray = camera.ScreenPointToRay(screentouch.position);
            if (screentouch.phase == TouchPhase.Began)
            {
                if (Physics.Raycast(ray, out RaycastHit hitInfo))
                {
                    if (hitInfo.collider.gameObject.GetComponent<co>() != null)
                    {
                        set = true;

                    }
                }
}

【问题讨论】:

标签: c# unity3d


【解决方案1】:

GetComponent&lt;T&gt; 是所谓的generic 方法。

泛型类型参数T 需要是编译时常量type,例如

Renderer renderer = someGameObject.GetComponent<Renderer>();

将返回Renderer 类型的实例。

var something = someGameObject.GetComponent<ISomeInterface>();

将返回 ISomeInterface 类型的实例。


GetComponent(Type type)GetComponent(string typeName) 的其他重载都返回最基本的类型 Component,为了正确使用它,您必须在之后类型转换结果。

同样的例子看起来像例如

Renderer renderer = (Renderer) someGameObject.GetComponent(typeof(Renderer));

Renderer renderer = (Renderer) someGameObject.GetComponent("Renderer");

因此,在您的情况下,您要么知道您正在寻找的类型,并且应该将其传递进去,或者如果您愿意,您可以使自己的方法也通用并执行

void move<T>()
{
    Touch screentouch = Input.GetTouch(0);
    Ray ray = camera.ScreenPointToRay(screentouch.position);
    if (screentouch.phase == TouchPhase.Began)
    {
        if (Physics.Raycast(ray, out RaycastHit hitInfo))
        {
            if (hitInfo.collider.gameObject.GetComponent<T>())
            {
                set = true;
            }
        }
   }
}

【讨论】:

    猜你喜欢
    • 2014-09-05
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    • 2020-05-10
    • 1970-01-01
    • 2013-06-04
    • 1970-01-01
    相关资源
    最近更新 更多