-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathUnitySingletonAttribute.cs
59 lines (50 loc) · 2.21 KB
/
UnitySingletonAttribute.cs
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 RSG.Utils;
using System;
using System.Linq;
using UnityEngine;
namespace RSG
{
/// <summary>
/// Attribute the defines a 'Unity Singleton', a MonoBehavior that is procedurally added to the scene and setup for dependency injection.
/// </summary>
public class UnitySingletonAttribute : SingletonAttribute
{
/// <summary>
/// Name of the single permanent object in the scene that contains all Unity singletons.
/// </summary>
public static readonly string UnitySingletonsGameObjectName = "_UnitySingletons";
public UnitySingletonAttribute()
{
}
public UnitySingletonAttribute(Type interfaceType) :
base(interfaceType)
{
}
/// <summary>
/// Set up a UnitySingleton for a specified type and platform.
/// </summary>
public UnitySingletonAttribute(Type interfaceType, params RuntimePlatform[] supportedPlatforms) :
base(interfaceType, () => supportedPlatforms.Contains(Application.platform))
{
}
public override object CreateInstance(IFactory factory, Type type)
{
Argument.NotNull(() => factory);
Argument.NotNull(() => type);
var unitySingletonHolder = GameObject.Find(UnitySingletonsGameObjectName);
if (unitySingletonHolder == null)
{
unitySingletonHolder = GameObjectCreator.CreatePermanentGameObject(UnitySingletonsGameObjectName);
}
// Instantiate the component.
var singletonComponent = (MonoBehaviour)unitySingletonHolder.AddComponent(type);
if (singletonComponent == null)
{
throw new ApplicationException(string.Format("Failed to add Unity singleton component {0} to GameObject {1}", type.Name, unitySingletonHolder.name));
//todo: throw new FormattedException("Failed to add Unity singleton component {SingletonTypeName} to GameObject {GameObjectName}", type.Name, unitySingletonHolder.name);
}
factory.ResolveDependencies(singletonComponent);
return singletonComponent;
}
}
}