- Home /
How to use Monobehaviour with an Interface
I'd like to instantiate a prefab and then check later if it has a firing script that makes it shoot at a designated target. But I'd like to pass it the target at runtime. Because Interfaces can't inherit from MonoBehaviour, I obviously can't do this:
public interface ICanFireAtTarget {
public AddTarget(GameObject target);
public FireAtTarget();
}
How can I achieve this behaviour then? How can check if an object has a script that can receive another gameObject as a target?
Answer by fafase · Jan 30, 2018 at 08:46 AM
First off, your interface declaration is wrong:
using UnityEngine;
public interface ICanFireAtTarget {
void AddTarget(GameObject target);
void FireAtTarget();
}
This will get you passed the compiler error.
Then your class can implement the interface:
public class MyClass : MonoBehaviour, ICanFireAtTarget
{
public void AddTarget(GameObject target){}
public void FireAtTarget(){}
}
and finally, since some Unity 5, interfaces can be found with GetComponent
void OtherMethod(GameObject obj)
{
ICanFireAtTarget temp = obj.GetComponent<ICanFireAtTarget >();
if(temp != null) { temp.AddTarget(someObject); }
}
Thank you and sorry for the public/void mixup, I'm just waking up :) I didn't know I could use GameObject in an interface. Visual Studio doesn't like it at all, saying that it doesn't know what GameObject is (which makes sense). And if I try to implement the interface anyway, I get an error saying that the object doesn't implement the first interface method (the one with GameObject). I don't see how I can do what you suggest, because GameObject doesn't exist in the interface's context (as I understand it):
public interface ICanFireAtTarget {
void AddTarget(GameObject target);
void FireAtTarget();
}
On the .cs file where your interface is declared, you need
using UnityEngine;
this will allow to use the GameObject class. Best way with interfaces to make sure you implement right, let the compiler implement for you. Add the interface to the class declaration:
public class $$anonymous$$yClass $$anonymous$$onoBehaviour , IInterface{}
then this will trigger an error that the class does not implement the interface. Right click on IInterface and click Resolve (2nd from top, it says more but I don't remember). This will show another popup with implement explicitly. Select that, now your class has the method with exceptions so you have to implement or it will trigger on call. But at least the compiler won't complain.
Just learned something new. I didn't know I could use "using" in an interface. Thanks a lot!
Your answer
![](https://koobas.hobune.stream/wayback/20220612151608im_/https://answers.unity.com/themes/thub/images/avi.jpg)