Skip to content

Commit 0e751e0

Browse files
committed
Simple spike of how I'd like the baseclass to work for the aggregator. No idea if it works yet but it's late and I'm tired so #yolo
1 parent d998cb6 commit 0e751e0

3 files changed

Lines changed: 57 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
}

src/UnityEventAggregator/EventAggregator.cs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff 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>

src/UnityEventAggregator/UnityEventAggregator.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
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" />

0 commit comments

Comments
 (0)