2017.11.7更新:
其實這個函數就是顧名思義,關鍵是理解AssetBundle, Asset, GameObject, 資源等之間的關系,參考此文即可:
http://www.cnblogs.com/88999660/archive/2013/03/15/2961663.html
---------------------------------羞恥的分割線-------------------------------------------
項目每60秒執行一次Resources.UnloadUnusedAssets。所以后續的GC不會一下子需要清理很多內存,所以游戲不會卡頓。
下面是查閱一下資料得到觀點,應該有錯漏,希望大神指正,謝謝。
1.
官方說法:An asset is deemed to be unused if it isn't reached after walking the whole game object hierarchy,
including script components. Static variables are also examined.
The script execution stack, however, is not examined so an asset referenced
only from within the script stack will be unloaded。
And, if necessary, loaded back in the next time one of its properties or methods is used.
This requires extra care for assets which have been modified in memory.
Make sure to call EditorUtility.SetDirty before an asset garbage collection is triggered.
我對上面的理解是,Resources.UnloadUnusedAssets只對Unity的組件腳本內的變量/屬性引用的資源和所有靜態變量引用的
(靜態類的成員引用也算,這里的引用包括多重引用)資源,進行unused標記unload,因為剩下的就是棧上變量(local variable)引用的資源,
這些資源會在變量出棧時unload掉(應該是類似UnloadUnusedAssets),如果這時要再使用這些資源,就需要重新load,即modified in memory。
這里的理解有誤的話,麻煩指出。
2.
現在的老大說,Resources.UnloadUnusedAssets只是標記,並不清理,並且不是標記為空閑(這個是GC干的,就是mono的清理,因為mono不歸還內存給os,只在mono層標記為空閑,os層還是使用中),只是把該塊內存降級,讓gc清理。
所以destroy an object后調Resources.UnloadUnusedAssets並沒有卵用,要等GC來了才生效。
3.
UnloadUnusedAssets - what exactly does "unused" mean:
1)靜態變量引用的資源;Monobehavior中變量/屬性引用的資源 視為“used”
2)被C#層強引用的資源,視為“used”
3) 弱引用被Unity視為“unused”,是會被清掉的;
但是(先GC.Collect,再UnloadUnusedAssets則暫時清不掉,下次GC.Collect才能,或者交換順序就能立刻清掉)
來源(已收入wiki):http://answers.unity3d.com/questions/910845/unloadunusedassets-what-exactly-does-unused-mean.html
4.
It only unloads assets that have been destroyed:
意思是我們Destroy掉的GameObject還是占着內存,被這個接口標記后才能被gc回收。
這個說法對嗎?
來源:http://answers.unity3d.com/questions/720239/does-unloadunusedassets-unload-non-active-or-occlu.html