Skip to content

Instantly share code, notes, and snippets.

@kibotu
Created January 29, 2015 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kibotu/f03cbdabb702639edc56 to your computer and use it in GitHub Desktop.
Save kibotu/f03cbdabb702639edc56 to your computer and use it in GitHub Desktop.
get component by interface from gameobject
public static T GetComponentByInterface<T>(this GameObject go) where T : class
{
var components = go.GetComponents<MonoBehaviour>();
foreach (var c in components)
{
T t = c as T;
if (t != null)
return t;
}
return null;
}
public static T[] GetComponentsByInterface<T>(this GameObject go) where T : class
{
var components = go.GetComponents<MonoBehaviour>();
var list = new List<T>();
foreach (var c in components)
{
T t = c as T;
if (t != null)
list.Add(t);
}
return list.ToArray();
}
public class TapableImpl : ITapable
{
public void Tapped()
{
}
}
public interface ITapable
{
void Tapped();
}
var tapable = hit.collider.gameObject.GetComponentByInterface<ITapable>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment