- 卸載獨立的資源: Resources.UnloadAsset(audioClip);
IEnumerator Start()
{
var audioClip = Resources.Load<AudioClip>("coin");
yield return new WaitForSeconds(5.0f);
Resources.UnloadAsset(audioClip);
Debug.Log("coin unloaded");
}
- 卸載不是獨立的資源, 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) 資源加載和卸載要成對使用
(2)避免重複加載資源
(3)避免錯誤的卸載掉還在使用的資源 -
避免重複加載資源
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;
}
- 優化,添加資源加載的記錄池
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;