[유니티] 동적리소스 관리(Memory Pool, ResourceManager)

using UnityEngine;
using System.Collections.Generic;

// GameObject vaPlayerObj = ResourceManager.CreateInstance("Player");
// OtherObj vaOtherObj = ResourceManager.CreateInstance("Other");
// ResourceManager.Get.Release();
public sealed class ResourceManager : MonoBehaviour
{
    private static ResourceManager ms_Instance;
    public static ResourceManager Get {
        get {
            if (ms_Instance == null)
                ms_Instance = new ResourceManager();
            return ms_Instance;
        }
    }

    private Dictionary<string, CACHED_OBJECT> m_hCachedObjTable = 
        new Dictionary<string, CACHED_OBJECT>();

    public struct CACHED_OBJECT
    {
        public enum eLinkType { RESOURCE, BUNDLE }
        public UnityEngine.Object obj;
        public eLinkType type;
        public AssetBundle bundle;
    }

    public T CreateInstance<T>(string strFilePath, bool bCaching = true) 
        where T : UnityEngine.Component
    {
        var vaObject = Load(strFilePath, bCaching);

        if (vaObject == null)
        {
            return default(T);
        }

        return ResourceManager.Instantiate<T>(vaObject);
    }

    public UnityEngine.Object Load(string path, bool bCaching)
    {
        UnityEngine.Object obj = null;

        obj = GetCachedObject(path);
        if (obj == null)
        {
            obj = Resources.Load(path);
            if(bCaching)
                AddCaching(path, obj, CACHED_OBJECT.eLinkType.RESOURCE);
        }

        return obj;
    }

    private UnityEngine.Object GetCachedObject(string strFilePath)
    {
        if (m_hCachedObjTable.ContainsKey(strFilePath))
        {
            return m_hCachedObjTable[strFilePath].obj;
        }
        
        return null;
    }

    private void AddCaching(string strFilePath, UnityEngine.Object obj, 
        CACHED_OBJECT.eLinkType eType, AssetBundle kAssetbundle = null)
    {
        if (obj == null)
        {
            return;
        }

        CACHED_OBJECT cache = new CACHED_OBJECT();
        cache.obj = obj;
        cache.type = eType;
        cache.bundle = kAssetbundle;

        if (m_hCachedObjTable.ContainsKey(strFilePath) == false)
        {
            m_hCachedObjTable[strFilePath] = cache;
        }
        
    }

    public static T Instantiate<T>(UnityEngine.Object obj) where T : UnityEngine.Object
    {
        if (obj == null)
        {
            return default(T);
        }

        return UnityEngine.Object.Instantiate(obj) as T;
    }


    public void Release()
    {
        AsyncOperation t;
        Release(out t);
    }

    public void Release(out AsyncOperation kRelease_AsyncOp)
    {
        var list = new List<CACHED_OBJECT>(m_hCachedObjTable.Values);
        m_hCachedObjTable.Clear();

        kRelease_AsyncOp = Resources.UnloadUnusedAssets();
    }
}

댓글

이 블로그의 인기 게시물

[유니티] 오류 사례 "Moving file failed", "Temp"

[유니티 사례] 비주얼 스튜디오(Visual Studio) 실행 오류

[유니티] 구글 지도 출력 샘플