본문 바로가기
개발/Unity

Unity) 싱글 톤 스크립터블 오브젝트 (ScriptableSingleton)

by 테샤르 2022. 1. 15.

싱글 톤 스크립터블 오브젝트 (ScriptableSingleton)

 

싱글 톤 스크립터블 오브젝트는 스크립터블을 전역에서 사용하기 위해서 static 하게 만드는 방법으로 Unity에서 지원하는 방식과 따로 구현하는 방식이 있다. 내부의 코드는 sigleton을 만드는 방식과 같다고 보면 된다.

 

<Sigleton Scripatable Object>

public class SingletonScripatableObject<T> : ScriptableObject where T : SingletonScriptableobject<T>
{
    private static T _instance;
    public static T Instance
    {
        get{
            if(_instance == null)
            {
                T[] asset = Resources.LoadAll<T>("");
                if(asset == null || asset.Length<1)
                {
                    throw new System.Exception($"Could not find any singleton scriptable object instance in the resource.");
                }
                else if( asset.Length> 1){
                    Debug.LogWarning("Multiple instance of the singleton scripate boject found in the resource.");
                }

                _instance =asset[0];
            }

            return _instance;
        }
    }
}

 

[CreateAssetMenu(fileName = "TestScriptableObject", menuName ="Scriptable Object/Test", order =1)]
public class TestScriptableObject : SingletonScripatableObject<TestScriptableObject>
{
    public string title;
    public int value;
}

<사용방법>

   title.text = $" {TestScriptableObject.Instance.title}";

 

스크립터블 오브젝트를 Genneric Singleton 형태로 사용하는 방식이다.

Unity에서 지원하는 방식은 Editor가 포함되어서 따로 구현하는 게 편하다.

반응형

실제 테스트해봤는데 굉장히 쓸만한 형태라고 생각한다.

스크립터블은 Unity에서 지원하는 데이터 컨테이너로 런타임 시에 사용하는 데이터 클래스라고 생각하면 된다.

여러 가지 형태의 데이터를 참조하거나 확인하기에도 굉장히 편하다.

싱글톤으로 만들어서 특정 데이터 값이라던지 빌드에 대한 정보 등등 여러 가지에서 활용할 수 있다.

 

 

원본 The BEST Unity Feature You Don't Know About - Scriptable Object Singletons Tutorial : [링크]

 

Unity Editor로 지원해주는 ScriptableSingleton<T> : [링크]

 

Unity - Scripting API: ScriptableSingleton<T0>

The ScriptableSingleton generic class allows you to create 'Manager' type classes in the Unity Editor. In classes that derive from ScriptableSingleton, serializable data you add survives assembly reloading in the Editor. Also, if the class uses the FilePat

docs.unity3d.com

 

 

★★★☆☆

 

반응형

댓글