Is it possible to get a reference to the gameObject from an interface?

5.5k views Asked by At

I've implemented an interface IVehicle for all vehicles in my game and would like to be able to get a reference to the gameObject whose script is attached to without using a gameObject property. Is this possible?

Something like:

IVehicle vehicle = GameObject.FindObjectOfType(typeof(IVehicle));
GameObject vehicleGO = vehicle.gameObject;
2

There are 2 answers

0
zambari On BEST ANSWER

Yes, there is a very easy solution. just place

GameObject gameObject { get ; } 

as part of your interface - all MonoBehaviours implement it, no extra steps needed. I add it to almost all my interfaces in Unity, it costs nothing and helps a lot

1
Programmer On

It is possible and an extra variable is not required. It's worth noting that you can't retrieve an interface in the scene with FindObjectOfType like you did in your question. You can only use FindObjectOfType with MonoBehaviour.

Get your interface:

using System.Linq;

IVehicle[] vehicles = FindObjectsOfType<MonoBehaviour>().OfType<IVehicle>().ToArray();

Cast to MonoBehaviour then you now can now access the GameObject that is linked with it

for (int i = 0; i < vehicles.Length; i++)
    GameObject vehicleGO = ((MonoBehaviour)vehicles[i]).gameObject;

Also, if you know the script name that implements the interface, no need to cast to MonoBehaviour. You can just cast to that script. Let's say the script that implements the IVehicle interface is named Car, you would just do something like this:

GameObject vehicleGO = ((Car)vehicles[i]).gameObject;