Unity 資源管理框架 《一》資源加載和卸載

  1. 卸載獨立的資源: Resources.UnloadAsset(audioClip);
IEnumerator Start()
		{
			var audioClip = Resources.Load<AudioClip>("coin");
			
			yield return new WaitForSeconds(5.0f);
			
			Resources.UnloadAsset(audioClip);
			
			Debug.Log("coin unloaded");
		}
  1. 卸載不是獨立的資源, Resources.UnloadUnusedAssets();
IEnumerator Start()
		{
			var homePanel = Resources.Load<GameObject>("HomePanel");
			
			yield return new WaitForSeconds(5.0f);


			homePanel = null;
			
			Resources.UnloadUnusedAssets();
			
			Debug.Log("homepanel unloaded");
			
		}
  1. 在一個頁面打開的時候,加載資源,在一個頁面關閉的時候卸載資源
    (1) 資源加載和卸載要成對使用
    (2)避免重複加載資源
    (3)避免錯誤的卸載掉還在使用的資源

  2. 避免重複加載資源

  private static Dictionary<string, object> AssetsDic = new Dictionary<string, object>();

    private T loadAsset<T>(string assetName) where T : Object
    {
        T asset = null;
        if (!AssetsDic.ContainsKey(assetName))
        {
            asset= Resources.Load<T>(assetName);
            AssetsDic.Add(assetName, asset);
        }
        else
        {
            asset = AssetsDic[assetName] as T;
        }
        return asset;      
    }
  1. 優化,添加資源加載的記錄池

    private static List<string> RecordPool = new List<string>(); //記錄池
    private static Dictionary<string, object> AssetsDic = new Dictionary<string, object>();   //資源池

    private T loadAsset<T>(string assetName) where T : Object
    {
        T asset = null;
        if (!AssetsDic.ContainsKey(assetName))
        {
            asset= Resources.Load<T>(assetName);
            AssetsDic.Add(assetName, asset);   //資源池
            RecordPool.Add(assetName);   //記錄池
        }
        else
        {
            asset = AssetsDic[assetName] as T;
        }
        return asset;   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章