1
1
using System ;
2
+ using System . Collections . Generic ;
2
3
using System . Linq ;
3
4
using System . Reflection ;
4
5
using UnityEngine ;
5
6
6
7
public static class MonoBehaviourExtensions {
7
8
9
+ public class Members {
10
+ public List < FieldInfo > Fields ;
11
+ public List < PropertyInfo > Properties ;
12
+ }
13
+
14
+ public static Dictionary < Type , Members > TypeMembers = new Dictionary < Type , Members > ( ) ;
15
+
8
16
public static void LoadComponents ( this MonoBehaviour behaviour ) {
17
+ var bType = behaviour . GetType ( ) ;
9
18
var cType = typeof ( ComponentAttribute ) ;
10
- var fields = behaviour . GetType ( ) . GetFields ( BindingFlags . Instance | BindingFlags . Public | BindingFlags . NonPublic )
11
- . Where ( f => f . GetCustomAttributes ( cType , true ) . Length == 1 ) . ToList ( ) ;
19
+ List < FieldInfo > fields ;
20
+ List < PropertyInfo > properties ;
21
+
22
+ if ( TypeMembers . ContainsKey ( bType ) ) {
23
+ var members = TypeMembers [ bType ] ;
24
+ fields = members . Fields ;
25
+ properties = members . Properties ;
26
+ } else {
27
+ fields = behaviour . GetType ( ) . GetFields ( BindingFlags . Instance | BindingFlags . Public | BindingFlags . NonPublic )
28
+ . Where ( f => f . GetCustomAttributes ( cType , true ) . Length == 1 ) . ToList ( ) ;
29
+ properties = behaviour . GetType ( ) . GetProperties ( BindingFlags . Instance | BindingFlags . Public | BindingFlags . NonPublic )
30
+ . Where ( p => p . GetCustomAttributes ( cType , true ) . Length == 1 ) . ToList ( ) ;
31
+
32
+ TypeMembers . Add ( bType , new Members ( ) {
33
+ Fields = fields ,
34
+ Properties = properties
35
+ } ) ;
36
+ }
12
37
13
38
foreach ( var item in fields ) {
14
39
var component = behaviour . GetComponent ( item . FieldType ) ;
@@ -21,9 +46,6 @@ public static void LoadComponents( this MonoBehaviour behaviour ) {
21
46
}
22
47
}
23
48
24
- var properties = behaviour . GetType ( ) . GetProperties ( BindingFlags . Instance | BindingFlags . Public | BindingFlags . NonPublic )
25
- . Where ( p => p . GetCustomAttributes ( cType , true ) . Length == 1 ) . ToList ( ) ;
26
-
27
49
foreach ( var item in properties ) {
28
50
var component = behaviour . GetComponent ( item . PropertyType ) ;
29
51
if ( component != null ) {
0 commit comments