- Home /
Retrieve Componet as Interface
I have a Class Damage that implements iDamage. When two objects collides I want to retrive the first component on the objects that implement iDamage and then apply damage. I cannot simply retrieve the Damage class from the objects because one day maybe I will have some object with SpecialDamage class that implements iDamage and the code will stop working. That's why I'm trying to use this static helper class
public static T RetrieveInterFace<T>(GameObject obj)
{
T _interface;
foreach (Component comp in obj.GetComponents<Component>())
{
if(comp is T)
{
_interface = (T) comp;
break;
}
}
return _interface;
}
But I can't make it work :|
Answer by pitimoi · Aug 06, 2013 at 05:03 PM
Hi,
You can make your function work like this :
public static class GameObjectExtention
{
public static T GetInterface<T>(this GameObject obj) where T : class
{
if(!typeof(T).IsInterface) return null;
T _interface = null;
foreach(Component c in obj.GetComponents(typeof(T)))
{
if(c is T)
{
_interface = c as T;
break;
}
}
return _interface;
}
}
I prefer using extentions for those kind of methods, you can easily use it with
IMyInterface i = myGameObject.GetInterface<IMyInterface>();
Some more infos can be found on this thread :
http://forum.unity3d.com/threads/60596-GetComponents-Possible-to-use-with-C-Interfaces
Your answer
Follow this Question
Related Questions
How to create an agenda or timetable system? 1 Answer
Script Component to implement interface 1 Answer
Ball delivery system ... back/down swing. 0 Answers
How do I make a Gui mouse interface? 0 Answers
Making dynamic login screen 1 Answer