Is there a beter (more style / more performant) way of getting the first (and hopefully only) component that implements a specific interface ?
public interface IFoo
{
void iFooMethod();
}
public class Foo
{
void OnCollisionEnter(Collision collision)
{
IFoo fooObject = null;
MonoBehaviour[] components = collision.transform.root.GetComponents();
foreach(MonoBehaviour component in components)
if(component is IFoo)
{
fooObject = component as IFoo;
break;
}
if(fooObject != null) fooObject.iFooMethod();
}
}
It just feels like I'm missing something ala GetComponentWithInterface.Blockquote
You can’t use the generic method, but this form seems to work fine:
IFoo foo = (IFoo)gameObject.GetComponent(typeof(IFoo));
Probably too late for the OP, but perhaps this helps someone else
.
As of Unity 5, you can use the generic form of GetComponent
on interfaces:
IFoo foo = gameObject.GetComponent<IFoo>();
IFoo[] foos = gameObject.GetComponents<IFoo>();
Alternatively, .GetComponent(typeof(IFoo))
works for old versions of Unity and .GetComponents(typeof(IFoo))
(with an ‘s’) also works from Unity 4.6 onwards.
I beleive that whole code block could be condensed down to the following:
void OnCollisionEnter(Collision collision)
{
collision.transform.root.GetComponent<IFoo>().iFooMethod();
}
y’all are making it way too complicated.
this works perfectly:
public class Hit : MonoBehaviour
{
void OnTriggerEnter(Collider other)
{
if (other.GetComponent<IDamageable>() != null)
{
print("HIT INTERFACE");
}
}
}