Created
March 6, 2019 12:39
-
-
Save marijnz/9a048b6c37d3cb7daa63d167eac6d829 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
using System; | |
using System.Collections.Generic; | |
using Assets.Scripts.Core; | |
using UnityEngine; | |
using Object = UnityEngine.Object; | |
public class Inject : Attribute { } | |
public class Controller | |
{ | |
public Controller() | |
{ | |
Injector.Inject(this); | |
Updater.Add(this); | |
} | |
} | |
public class Injector | |
{ | |
static Dictionary<Type, object> objects = new Dictionary<Type, object>(); | |
public static T Get<T>() | |
{ | |
return (T) Get(typeof(T)); | |
} | |
static object Get(Type type) | |
{ | |
object obj; | |
objects.TryGetValue(type, out obj); | |
if(obj == null) | |
{ | |
if(typeof(Object).IsAssignableFrom(type)) | |
{ | |
obj = Object.FindObjectOfType(type); | |
Debug.Assert(obj != null, "Couldn't find view for " +type); | |
} | |
else | |
{ | |
obj = Activator.CreateInstance(type); | |
} | |
objects[type] = obj; | |
} | |
return obj; | |
} | |
public static void Inject(object obj) | |
{ | |
foreach (var field in obj.GetType().GetFieldsWithAttribute<Inject>()) | |
{ | |
var fieldObj = Get(field.FieldType); | |
field.SetValue(obj, fieldObj); | |
} | |
} | |
public static void Clear() | |
{ | |
objects.Clear(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment