I have several scenes where each scene has a GameObject with a single script attached to it, where that script implements some interface.
Is there a way to find the GameObject instance, searching by interface type?
I have several scenes where each scene has a GameObject with a single script attached to it, where that script implements some interface.
Is there a way to find the GameObject instance, searching by interface type?
If you’re using an old version of Unity, just use LINQ.
using System.Linq;
...
var comps = GetComponents<MonoBehaviour>().OfType<MyInterface>();
If you’re looking for something that isn’t a subclass of MonoBehaviour
, then just broaden the search by replacing MonoBehaviour
in the snippet above with Behaviour
, or Component
. You can use this same trick with FindObjectsOfType<T>()
.
FindObjectOfType will only works with components. I think you’ll need to find all the gameobjects in the scene and check if they implement that interface( with if( … is … ) ).
You could as well use a singleton.