Need help with generic method.

[SOLVED]

I have trouble understanding how to write this piece of code.
for instance:

void Start()
{
        //To find all Fonts in InputField Text components
        FindAllFonts<InputField>();
}

void FindAllFonts<T>()
{
      //How to let my code now what objecttype it is.
      //if I eg want to use T[]  tempObject =  FindObjectsOfType<T>();
      //I can't use T directly but still want to keep it completely generic
}

I tried a lot of approaches but mostly get this error:
//
Severity Code Description Project File Line Suppression State
Error CS0314 The type ‘T’ cannot be used as type parameter ‘T’ in the generic type or method ‘Object.FindObjectsOfType()’. There is no boxing conversion or type parameter conversion from ‘T’ to ‘UnityEngine.Object’. UIPath_Prototyping01 E:\Unity Projects\Projects\UIPath_Prototyping01\Assets\Resources\Scripts\UITech\UIFactory.cs 91 Active
//

You need to add a constraint to your generic to prevent using types not supported by FindObjectsOfType (like ints or strings).

void FindAllFonts<T>() where T : UnityEngine.Object
{
 T[] objects = GameObject.FindObjectsOfType<T>();
}

Though I will say this seems like a silly design in the first place and going to be very, very slow. You’re much better off just finding specific GOs and then using a GetComponent<> call.

1 Like

@GroZZleR
Thanks!
Didn’t know about the existence of UnityEngine.Object.
Had tried different constrainst but none were working.

And don’t worry about being slow, it is for use in Editor and not game :slight_smile: