Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 057a4e3

Browse files
SceneSingleton
1 parent 552733a commit 057a4e3

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-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+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /