【Unity3D 踩坑】RenderTexture复用

原来使用特效一直都是创建-使用-销毁

//引用RenderTexture
RenderTexture renderTexture = new RenderTexture(width, height, depth, format);
camera.targetTexture = renderTexture;
rawImage.texture = renderTexture;

//销毁RenderTexture
rawImage.texture = null;
GameObject.Destroy(camera.gameObject);
GameObject.Destroy(renderTexture);
renderTexture = null;

然后某天优化的时候,考虑到频繁创建销毁会加快GC的到来,于是代码修改成

//引用RenderTexture
RenderTexture renderTexture = RenderTextureCache.Get(width, height, depth, format);
camera.targetTexture = renderTexture;
rawImage.texture = renderTexture;

//销毁RenderTexture
RenderTextureCache.Return(renderTexture);
rawImage.texture = null;
GameObject.Destroy(camera.gameObject);
//GameObject.Destroy(renderTexture);//不必要的销毁操作,我们可以把它放回缓存池
renderTexture = null;

重点来了,偶现Unity报错:Releasing render texture that is set as Camera.targetTexture!

问题重现:同一帧内,先去掉RenderTexture的引用,再给RenderTexture加上引用,就会导致这个报错,报错之后,相机就不会把渲染结果输出到RenderTexture里去,最终看到的图是一片白色的!

据说是Unity的Bug,我的版本是5.3.5f1,这个Bug在Unity5.6解决了,由于不能换版本,只好另寻办法。

解决办法:延迟一帧设置camera.targetTexture以及rawImage.texture

//引用RenderTexture
Invoke("SetRTCamera", 0.01f);

private void SetRTCamera()
{
    RenderTexture renderTexture = RenderTextureCache.Get(width, height, depth, format);
    camera.targetTexture = renderTexture;
    rawImage.texture = renderTexture;
}

你可能感兴趣的:(移动开发,Unity3D)