Generics help passing object type parameter rather than an object.

How can I make this work? I want to pass in the name and type of control that I’m looking for, and return the object with generics. However I can’t seem to get it to work with the object type parameter. And I don’t want to pass an object into it.

Build error line #4: ‘Text’ is a type, which is not valid in the given context.

    private void Start()
    {
        Text myTextBox = GetControl("txtMsg", Text);
    }

    public T GetControl<T>(string controlname, T type) where T : UnityEngine.Object
    {
        return GameObject.Find(controlname).gameObject.GetComponent<T>();
    }

I know I can pass in an Text object in the parameter but I don’t want to do that. I just want to specify the type of object i want it to return.

Any help is much appreciated. Thanks

I imagine you would need at a minimum to use typeof(Text) as the argument.

But I’m puzzled about specifying the type both as generic and argument.

Wouldn’t you just call it as var mytb = GetControl<Text>( "txtMsg"); ?

Also, before you go too far down this dark rabbit hole of thinly-wrapping GetComponent() with a string search field:

Remember the first rule of GameObject.Find():

Do not use GameObject.Find();

More information: Regarding GameObject.Find · UnityTipsRedux

1 Like

Can you not just call GetControl<Text>("txtMsg") without the type parameter?

2 Likes

Ah ha! Yes! This is what I was looking for. Just couldn’t get the syntax right. It’s a monday… I blame that. hahaha
Thanks guys.

GetControl<Text>("txtMsg")