구글에 unity singleton template을 검색하면 여러가지 예제 코드가 나올 것이다.

그중에서 unifywiki에 있는 코드를 사용하였다.


http://wiki.unity3d.com/index.php/Singleton


위 링크를 들어가면 singleton에 대한 설명과 singleton을 구현해둔 singleton.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using UnityEngine;
 
/// <summary>
/// Be aware this will not prevent a non singleton constructor
///   such as `T myT = new T();`
/// To prevent that, add `protected T () {}` to your singleton class.
/// 
/// As a note, this is made as MonoBehaviour because we need Coroutines.
/// </summary>
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;
 
    private static object _lock = new object();
 
    public static T Instance
    {
        get
        {
            if (applicationIsQuitting) {
                Debug.LogWarning("[Singleton] Instance '"+ typeof(T) +
                    "' already destroyed on application quit." +
                    " Won't create again - returning null.");
                return null;
            }
 
            lock(_lock)
            {
                if (_instance == null)
                {
                    _instance = (T) FindObjectOfType(typeof(T));
 
                    if ( FindObjectsOfType(typeof(T)).Length > 1 )
                    {
                        Debug.LogError("[Singleton] Something went really wrong " +
                            " - there should never be more than 1 singleton!" +
                            " Reopening the scene might fix it.");
                        return _instance;
                    }
 
                    if (_instance == null)
                    {
                        GameObject singleton = new GameObject();
                        _instance = singleton.AddComponent<T>();
                        singleton.name = "(singleton) "+ typeof(T).ToString();
 
                        DontDestroyOnLoad(singleton);
 
                        Debug.Log("[Singleton] An instance of " + typeof(T) + 
                            " is needed in the scene, so '" + singleton +
                            "' was created with DontDestroyOnLoad.");
                    } else {
                        Debug.Log("[Singleton] Using instance already created: " +
                            _instance.gameObject.name);
                    }
                }
 
                return _instance;
            }
        }
    }
 
    private static bool applicationIsQuitting = false;
    /// <summary>
    /// When Unity quits, it destroys objects in a random order.
    /// In principle, a Singleton is only destroyed when application quits.
    /// If any script calls Instance after it have been destroyed, 
    ///   it will create a buggy ghost object that will stay on the Editor scene
    ///   even after stopping playing the Application. Really bad!
    /// So, this was made to be sure we're not creating that buggy ghost object.
    /// </summary>
    public void OnDestroy () {
        applicationIsQuitting = true;
    }
}
cs



그리고 나와있는 사용법대로 적용하면된다.

클래스가 기본적으로 상속받고 있는 Monobehavior를 지워버리고 대신에 Singleton<class명>을 상속받으면 된다.

1
2
3
4
5
6
7
public class GameData : Singleton<GameData> {
    protected GameData() { }
 
    public int GameQuality = 5;
    public float BgmVolume = 1.0f;
    public bool BgmOn = true;
}
cs



사용할 때는 싱글톤처럼 사용하면되고 클래스이름을 치면 알아서 Instance가 뜬다.

1
2
3
var BGM = GameObject.FindGameObjectWithTag("BGM").GetComponent<AudioSource>();
SettingCanvas.GetComponentInChildren<Slider>().value = GameData.Instance.BgmVolume;
SettingCanvas.GetComponentInChildren<Toggle>().isOn = GameData.Instance.BgmOn;
cs


Posted by misty_
,