- Home /
Is it possible to find a script instance by the 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?
Answer by Lichter · Mar 17, 2018 at 03:54 PM
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>()
.
This question has been for 6 years and you should not answer such an old question. However, if you are looking for an answer, I have a few suggestions, I believe it is faster than using LINQ. Ins$$anonymous$$d of inheriting it from the class $$anonymous$$onoBehaviour and the interface, you can inherit your class from $$anonymous$$y$$anonymous$$onoBehaviour: $$anonymous$$onoBehaviou and the interfacer, then use FindObjectOfType< $$anonymous$$y$$anonymous$$onoBehaviour> (). Also note, jacksmash2012 would like to search for this component in Hierarchy, not on the current gameobject.