2019独角兽企业重金招聘Python工程师标准>>>

先上代码:

Object o;

GameObject go;

void Start()

{

    o = Resource.Load("pic");

    go = (GameObject)Instantiate(o);

    StartCoroutine(WaitAndPrint(2.0F));

}

IEnumerator WaitAndPrint(float time)

{

    yield return new WaitForSeconds(time);

    Resource.UnloadAsset(o);

}

今天在测试资源卸载的时候,报了一个错:

UnloadAsset may only be used on individual assets and can not be used on 

GameObject's/Components or AssetBundles

妈蛋,它的API上压根就没写过这东西:http://docs.unity3d/ScriptReference/Resources.UnloadAsset.html

所以,得分析一下什么是属于individual assets。

首先想到的是图片texture,经过测试,确实是释放成功的。

观察Unity资源释放是否成功的工具是Unity Profiler --> 选中Memory模块 -->选中detailed模式 -->运行程序

--》然后选中一帧take Sample,Profiler就会给把该帧上的一些内存数据真是出来,然后展开Assets栏,找到Texture2D就可以看到自己加载的图片,然后等它运行到Reource.UnloadAsset之后,再选一帧来Take Sample,就可以看到Asset上已经没有了该图片。

然后就是Material....也是释放成功的...其他的就不测试了..

mesh / texture / material / shader 


所以如果我要卸载掉GameObject的话,使用Resources.UnloadUnusedAssets():


Object o;

GameObject go;

void Start()

{

    o = Resource.Load("pic");

    go = (GameObject)Instantiate(o);

    StartCoroutine(WaitAndPrint(2.0F));

}

IEnumerator WaitAndPrint(float time)

{

    yield return new WaitForSeconds(time);

    o = null; //这句话好加,不然卸载不了

    Resource.UnloadUnusedAssets();

    Destroy(pic);

}

观察Profiler,是成功的。


卸载Instantiate出来的GameObject:  Destroy(GameObject)

卸载GameObject的时候,挂载在其上面的脚本同时也会被卸载




转载于:https://my.oschina/u/185335/blog/384651

更多推荐

Resource.UnloadAsset卸载资源的小知识