Resources.UnloadUnusedAssets

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

原文地址:https://www.cnblogs.com/Tearix/p/6844956.html