Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you find objects of a type which takes in 2 generic types, but regardless of those types?

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?

like image 910
User42389041 Avatar asked Jan 17 '26 23:01

User42389041


1 Answers

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?

like image 154
derHugo Avatar answered Jan 19 '26 14:01

derHugo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!