File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . Linq ;
4+ using UnityEngine ;
5+
6+ namespace UnityEventAggregator
7+ {
8+ public class BaseClass : MonoBehaviour
9+ {
10+ void Start ( )
11+ {
12+ GetListenerTypes ( ) . Each ( x => EventAggregator . Register ( this , x ) ) ;
13+ }
14+
15+ void OnDestroy ( )
16+ {
17+ GetListenerTypes ( ) . Each ( x => EventAggregator . UnRegister ( this , x ) ) ;
18+ }
19+
20+ IEnumerable < Type > GetListenerTypes ( )
21+ {
22+ return GetType ( )
23+ . GetInterfaces ( )
24+ . Where ( x => x . IsGenericType )
25+ . Where ( x => x . GetGenericTypeDefinition ( ) == typeof ( IListener < > ) )
26+ . Select ( x => x . GetGenericArguments ( ) )
27+ . First ( ) ;
28+ }
29+ }
30+ }
Original file line number Diff line number Diff line change @@ -34,6 +34,32 @@ public static void UnRegister<T>(this T obj) where T : struct
3434 _cache [ typeof ( T ) ] . Remove ( obj ) ;
3535 }
3636
37+ /// <summary>
38+ /// Register the game object to listen for events of type T.
39+ /// </summary>
40+ /// <typeparam name="T">The type of event being listened for.</typeparam>
41+ /// <param name="obj"></param>
42+ /// <param name="listener"></param>
43+ public static void Register ( object obj , Type listener )
44+ {
45+ if ( ! _cache . ContainsKey ( listener ) )
46+ _cache [ listener ] = new List < object > ( ) ;
47+
48+ _cache [ listener ] . Add ( obj ) ;
49+ }
50+
51+ /// <summary>
52+ /// Removes the registration for listening to events of type T.
53+ /// </summary>
54+ /// <typeparam name="T">The type of event to no longer listen for.</typeparam>
55+ /// <param name="obj"></param>
56+ /// <param name="listener"></param>
57+ public static void UnRegister ( object obj , Type listener )
58+ {
59+ if ( ! _cache . ContainsKey ( listener ) ) return ;
60+ _cache [ listener ] . Remove ( obj ) ;
61+ }
62+
3763 /// <summary>
3864 /// Notifies all listeners of event type T.
3965 /// </summary>
Original file line number Diff line number Diff line change 4343 </Reference >
4444 </ItemGroup >
4545 <ItemGroup >
46+ <Compile Include =" BaseClass.cs" />
4647 <Compile Include =" EventAggregator.cs" />
4748 <Compile Include =" Extensions.cs" />
4849 <Compile Include =" IListener.cs" />
You can’t perform that action at this time.
0 commit comments