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 :expressionless:

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