Home > front end >  what is the type of the GetComponent<"type">()? in unity
what is the type of the GetComponent<"type">()? in unity

Time:12-27

I need to write a function and input the value in it I try to use string, then GetType and it's no work. and use MonoBehaviour it ;s no work. and i missing something??

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;

                    }
                }
}

CodePudding user response:

GetComponent<T> is a so called generic method.

The generic type parameter T needs to be a compile time constant type like e.g.

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

will return an instance of type Renderer.

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

will return an instance of type ISomeInterface.


The other overloads both GetComponent(Type type) and GetComponent(string typeName) both return the most basic type Component and in order to properly work with it you have to type cast the result afterwards.

Same example would look like e.g.

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

or

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

So in your case you either know the type you are looking for and should pass that one in or if you want you can make your own method also generic and do

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;
            }
        }
   }
}
  • Related