Skip to content

Commit 040576c

Browse files
authored
Merge pull request #6 from starryforest-ymxk/master
Scene Singleton Pattern
2 parents 552733a + f8d0572 commit 040576c

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

Assets/Scripts/SceneSingleton.cs

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
using System.Collections;
2+
using System.Collections.Generic;
3+
using UnityEngine;
4+
5+
// "Scene Singleton Pattern" or "Local Singleton Pattern"
6+
// It differs from the traditional "Global singleton pattern",
7+
// The purpose of "Scene Singleton Pattern" is to ensure that there is only one instance of the class in a given scene, but it does not require that instance to persist across scenes.
8+
// This pattern is useful when you need to manage certain assets or features in a single scene, but you don't want those assets or features to remain present when the scene is switched.
9+
10+
public abstract class SceneSingleton<T> : MonoBehaviour where T : Component
11+
{
12+
13+
#region Fields
14+
15+
/// <summary>
16+
/// The instance.
17+
/// </summary>
18+
private static T instance;
19+
20+
#endregion
21+
22+
#region Properties
23+
24+
/// <summary>
25+
/// Gets the instance.
26+
/// </summary>
27+
/// <value>The instance.</value>
28+
public static T Instance
29+
{
30+
get
31+
{
32+
if (instance == null)
33+
{
34+
instance = FindObjectOfType<T>();
35+
if (instance == null)
36+
{
37+
GameObject obj = new GameObject();
38+
obj.name = typeof(T).Name;
39+
instance = obj.AddComponent<T>();
40+
}
41+
}
42+
return instance;
43+
}
44+
}
45+
46+
#endregion
47+
48+
#region Methods
49+
50+
/// <summary>
51+
/// Use this for initialization.
52+
/// </summary>
53+
protected virtual void Awake()
54+
{
55+
if (instance == null)
56+
{
57+
instance = this as T;
58+
}
59+
else
60+
{
61+
Destroy(gameObject);
62+
}
63+
}
64+
65+
#endregion
66+
67+
}

Assets/Scripts/SceneSingleton.cs.meta

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)