3

Odd title, i know.

Basically, if you have a class e.g.:

public class SomeClass<T1, T2> : MonoBehaviour {}

is there any way to do something like this, FindObjectsOfType<SomeClass<>>(), and retrieve all existing SomeClass regardless of T1 and T2?

derHugo
  • 83,094
  • 9
  • 75
  • 115

1 Answers1

1

No, not directly.

You can however use a little trick: Create a non-generic base class for it

public abstract class SomeBase : MonoBehaviour { }

public class SomeClass<T1, T2> : SomeBase { }

Now you can simply use

SomeBase[] instances = FindObjectsOfType<SomeBase>();

However this returns only the SomeBase type and you wouldn't get access to inner stuff of SomeClass. It is enough to access e.g. transform or gameObject.

You could add some abstract properties in order to be able to convert them to the correct type later:

public abstract class SomeBase : MonoBehaviour
{
    public abstract Type GetT1 { get; }
    public abstract Type GetT2 { get; }
}

public class SomeClass<T1, T2> : SomeBase
{
    public override Type GetT1
    {
        get { return typeof(T1); }
    }

    public override Type GetT2
    {
        get { return typeof(T2); }
    }
}

Now you can simply do e.g.

var test = FindObjectsOfType<SomeBase>();
foreach (var someClass in test)
{
    Debug.LogFormat("Instance found on {0}: T1={1}, T2={2}", someClass.name, someClass.GetT1.Name, someClass.GetT2.Name);
}

To further typecast the items to the target SomeClass I think you would need to use reflection. There are some examples like e.g. How to cast a generic type at runtime in c# or also Cast generic type without knowing T?

derHugo
  • 83,094
  • 9
  • 75
  • 115