Generic Method Woes : Cannot convert type 'UnityEngine.Object' to 'T'

Howdy. Thanks for reading me. =D

I’m currently trying to create a generic method based from the method bellow. :

    // Return all gizmos
    GameObject[] FindAllSceneGizmos()
    {
        Object[] objectT = Object.FindObjectsOfType(typeof(ShowGizmo));
        GameObject[] allObjectsT = new GameObject[objectT.Length];

        for (int i = 0; i < objectT.Length; i++)
        {
            allObjectsT _= ((ShowGizmo)objectT*).gameObject;*_

}

return allObjectsT;

}
The above method works absolutely fine. If I change ShowGizmo to any class derived from Monobehaviour it works fine. Since the method has multiple uses, a generic method seems to fit well (not a fan of duplicates). I created this generic method :
// Return all objects of type T
GameObject[] FindAll()
{
Object[] objectT = Object.FindObjectsOfType(typeof(T));
GameObject[] allObjectsT = new GameObject[objectT.Length];

for (int i = 0; i < objectT.Length; i++)
{
allObjectsT = ((T)objectT*).gameObject;*
}

return allObjectsT;

}
This is when I get the error Cannot convert type ‘UnityEngine.Object’ to ‘T’. It makes sense since the compiler doesn’t know if T is derived from Monobehaviour? Any class that doesn’t derive from it I get the same error message.
I feel like I’m close to finding a solution, thanks for anyone who considers helping me out. :slight_smile:

GameObject FindAll () where T: MonoBehaviour

You need to add a type constraint to your generic method declaration.

	GameObject[] FindAll<T>() where T : Component {
	
		T[] Tarr = GameObject.FindObjectsOfType<T>();
		GameObject[] gameObjectArr = new GameObject[Tarr.Length];
		
		for (int i = 0; i < Tarr.Length; i++)
		{
			gameObjectArr _= Tarr*.gameObject;*_

* }*

* return gameObjectArr;*

* }*
This way you’ll be able to find anything derived from component, like transforms, monobehaviours you’ve written, canvases, colliders, ect.

public static GameObject FindAll() where T:MonoBehaviour
{
MonoBehaviour objectT = ((MonoBehaviour)UnityEngine.Object.FindObjectsOfType(typeof(T)));
GameObject allObjectsT = new GameObject[objectT.Length];

    for (int i = 0; i < objectT.Length; i++)
    {
        allObjectsT _= objectT*.gameObject;*_

}
return allObjectsT;
}