Skip to content

Commit 4646eb3

Browse files
committed
Added type check to Single<T>.Bind
1 parent 05f7549 commit 4646eb3

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

Assets/Kekser/PowerSingleton/Single.cs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ namespace Kekser.PowerSingleton
44
{
55
public static class Single<T> where T : class
66
{
7-
private static Object _rawInstance;
7+
private const string PowerSingletonCantBind = "PowerSingleton: Can't bind {0} to {1}";
8+
9+
private static Object _rawInstance { get; set; }
810
private static T _instance { get; set; }
911

1012
public static T Instance {
@@ -18,8 +20,19 @@ public static T Instance {
1820

1921
public static void Bind(Object instance)
2022
{
23+
if (instance == null)
24+
{
25+
_rawInstance = null;
26+
_instance = null;
27+
return;
28+
}
29+
if (!(instance is T tInstance))
30+
{
31+
Debug.LogErrorFormat(PowerSingletonCantBind, instance.GetType(), typeof(T));
32+
return;
33+
}
2134
_rawInstance = instance;
22-
_instance = instance as T;
35+
_instance = tInstance;
2336
}
2437
}
2538
}

Assets/Kekser/PowerSingleton/package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
"name": "com.kekser.powersingleton",
33
"displayName": "PowerSingleton",
44
"author": { "name": "Kekser", "url": "https://github.com/DerKekser" },
5-
"version": "1.3.0",
5+
"version": "1.3.1",
66
"unity": "2020.3",
77
"description": "A simple singleton system for Unity",
88
"keywords": [ "singleton" ],

Assets/Kekser/Tests/PowerSingletonTests.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,20 @@ public IEnumerator TestBindSingleton()
113113
Assert.IsTrue(BindSingleton.Created);
114114
Assert.IsNotNull(Single<BindSingleton>.Instance);
115115
}
116+
117+
[UnityTest]
118+
[LoadScene("Assets/Kekser/Tests/Scenes/PowerSingletonTestScene.unity")]
119+
public IEnumerator TestBindWrongSingleton()
120+
{
121+
yield return null;
122+
Assert.IsFalse(BindSingleton.Created);
123+
Single<BindSingleton>.Bind(new GameObject("BindSingleton").AddComponent<DefaultSingleton>());
124+
LogAssert.Expect(LogType.Error, "PowerSingleton: Can't bind Kekser.Tests.DefaultSingleton to Kekser.Tests.BindSingleton");
125+
yield return null;
126+
Assert.IsFalse(BindSingleton.Created);
127+
Assert.IsNull(Single<BindSingleton>.Instance);
128+
LogAssert.Expect(LogType.Error, "PowerSingletonManager: No PowerSingletonAttribute for type Kekser.Tests.BindSingleton, and no instance in scene");
129+
}
116130
}
117131

118132
public class LoadSceneAttribute : NUnitAttribute, IOuterUnityTestAction

0 commit comments

Comments
 (0)