-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGameObjectExtensions.cs
More file actions
59 lines (52 loc) · 2.19 KB
/
GameObjectExtensions.cs
File metadata and controls
59 lines (52 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
using System;
using UnityEngine;
using System.Linq;
public static class GameObjectExtensions
{
/// <summary>
/// Returns all monobehaviours (casted to T)
/// </summary>
/// <typeparam name="T">interface type</typeparam>
/// <param name="gObj"></param>
/// <returns></returns>
public static T[] GetInterfaces<T>(this GameObject gObj)
{
if (!typeof(T).IsInterface) throw new SystemException("Specified type is not an interface!");
var mObjs = gObj.GetComponents<MonoBehaviour>();
return (from a in mObjs where a.GetType().GetInterfaces().Any(k => k == typeof(T)) select (T)(object)a).ToArray();
}
/// <summary>
/// Returns the first monobehaviour that is of the interface type (casted to T)
/// </summary>
/// <typeparam name="T">Interface type</typeparam>
/// <param name="gObj"></param>
/// <returns></returns>
public static T GetInterface<T>(this GameObject gObj)
{
if (!typeof(T).IsInterface) throw new SystemException("Specified type is not an interface!");
return gObj.GetInterfaces<T>().FirstOrDefault();
}
/// <summary>
/// Returns the first instance of the monobehaviour that is of the interface type T (casted to T)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="gObj"></param>
/// <returns></returns>
public static T GetInterfaceInChildren<T>(this GameObject gObj)
{
if (!typeof(T).IsInterface) throw new SystemException("Specified type is not an interface!");
return gObj.GetInterfacesInChildren<T>().FirstOrDefault();
}
/// <summary>
/// Gets all monobehaviours in children that implement the interface of type T (casted to T)
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="gObj"></param>
/// <returns></returns>
public static T[] GetInterfacesInChildren<T>(this GameObject gObj)
{
if (!typeof(T).IsInterface) throw new SystemException("Specified type is not an interface!");
var mObjs = gObj.GetComponentsInChildren<MonoBehaviour>();
return (from a in mObjs where a.GetType().GetInterfaces().Any(k => k == typeof(T)) select (T)(object)a).ToArray();
}
}