- Home /
Find a Component/GameObject Using an Interface Reference
In my script, I have a reference to an "IDamageable" interface. How would I be able to find the component that the Interface is attached to? Or the gameobject the component is attached to? Example:
public class Obj : MonoBehaviour
{
IDamagable<DamageInfo> damagable;
// Use this for initialization
void Awake ()
{
GameObject g = damagable.gameObject; //How would I get this?
MonoBehaviour m = damagable.monoBehaviour; //Or this?
}
}
Sorry if this question has been asked before, Google kept showing me unrelated questions.
Answer by merckerrobert · Dec 03, 2018 at 10:10 PM
Another way this can be done if you don't want to cast would be to have the interface create a blank function like getGameObject that returns a GameObject. The implementing class would have to define what the function does and can return its gameObject.
public interface interfaceName {
GameObject getGameObject();
}
public class className : MonoBehavior, interfaceName {
public GameObject getGameObject() {
return gameObject;
}
}
Answer by Bunny83 · Jun 23, 2016 at 08:48 PM
An interface is not attached to something. A class can implement an interface. An interface basically acts like a seperate base class. So at any time you can cast the reference to the actual type if you know it. If all classes that implement are MonoBehaviour scripts you can always cast the reference to MonoBehaviour or Component. This gives you access to "transform" or "gameObject". If you want to access more specific things you would need to know the actual type so you can cast the reference accordingly
The easiest way is to use an "as"-cast in conjunction with a null check.
MonoBehaviour mb = damagable as MonoBehaviour;
if (mb != null)
{
GameObject g = mb.gameObject;
// [...]
}
Nice solution. I struggled with this and this solves my problem. Thanks!
Do you know a good way of tagging classes that could reference something like an event.