Unity 资源管理框架 《一》资源加载和卸载

  1. 卸载独立的资源: Resources.UnloadAsset(audioClip);
IEnumerator Start()
		{
			var audioClip = Resources.Load("coin");
			
			yield return new WaitForSeconds(5.0f);
			
			Resources.UnloadAsset(audioClip);
			
			Debug.Log("coin unloaded");
		}
  1. 卸载不是独立的资源, Resources.UnloadUnusedAssets();
IEnumerator Start()
		{
			var homePanel = Resources.Load("HomePanel");
			
			yield return new WaitForSeconds(5.0f);


			homePanel = null;
			
			Resources.UnloadUnusedAssets();
			
			Debug.Log("homepanel unloaded");
			
		}
  1. 在一个页面打开的时候,加载资源,在一个页面关闭的时候卸载资源
    (1) 资源加载和卸载要成对使用
    (2)避免重复加载资源
    (3)避免错误的卸载掉还在使用的资源

  2. 避免重复加载资源

  private static Dictionary AssetsDic = new Dictionary();

    private T loadAsset(string assetName) where T : Object
    {
        T asset = null;
        if (!AssetsDic.ContainsKey(assetName))
        {
            asset= Resources.Load(assetName);
            AssetsDic.Add(assetName, asset);
        }
        else
        {
            asset = AssetsDic[assetName] as T;
        }
        return asset;      
    }
  1. 优化,添加资源加载的记录池

    private static List RecordPool = new List(); //记录池
    private static Dictionary AssetsDic = new Dictionary();   //资源池

    private T loadAsset(string assetName) where T : Object
    {
        T asset = null;
        if (!AssetsDic.ContainsKey(assetName))
        {
            asset= Resources.Load(assetName);
            AssetsDic.Add(assetName, asset);   //资源池
            RecordPool.Add(assetName);   //记录池
        }
        else
        {
            asset = AssetsDic[assetName] as T;
        }
        return asset;   

你可能感兴趣的:(unity,资源加载框架)