Created
January 29, 2015 10:20
-
-
Save kibotu/f03cbdabb702639edc56 to your computer and use it in GitHub Desktop.
get component by interface from gameobject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TapableImpl : ITapable | |
{ | |
public void Tapped() | |
{ | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface ITapable | |
{ | |
void Tapped(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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