gpt4 book ai didi

c# - 当 Camera.targetTexture = new RenderTexture(...) 时内存泄漏

转载 作者:行者123 更新时间:2023-12-03 08:58:30 27 4
gpt4 key购买 nike

我编写了一个 EditorWindow,它将摄像机的 View 渲染到另一个编辑器窗口中。为了在窗口大小调整时立即适应,在tick时间重新分配相机的目标纹理(实际上只在必要时才这样做)以演示问题:

public class PlayerViewWindow : EditorWindow
{
private Camera PlayerViewCamera; // References a camera in the scene

public void OnGUI()
{
PlayerViewCamera.targetTexture = new RenderTexture((int)position.width, (int)position.height, 24, RenderTextureFormat.ARGB32);
PlayerViewCamera.Render();
GUI.DrawTexture(new Rect(0, 0, position.width, position.height), PlayerViewCamera.targetTexture);
}
}

当我激活此窗口时,相机目标纹理的重新分配会导致内存泄漏。那么:为什么旧的目标纹理没有被垃圾收集呢?有没有办法显式地销毁旧的目标纹理?

谢谢

最佳答案

来自RenderTexture Documentation :

As with other "native engine object" types, it is important to pay attention to the lifetime of any render textures and release them when you are finished using them with the Release function, as they will not be garbage collected like normal managed types.

所以只需调用 Release()在附加新的渲染纹理之前,先在旧的 RenderTexture 上:

public class PlayerViewWindow : EditorWindow
{
private Camera PlayerViewCamera; // References a camera in the scene

public void OnGUI()
{
if(PlayerViewCamera.targetTexture != null)
{
PlayerViewCamera.targetTexture.Release();
}

PlayerViewCamera.targetTexture = new RenderTexture((int)position.width, (int)position.height, 24, RenderTextureFormat.ARGB32);
PlayerViewCamera.Render();
GUI.DrawTexture(new Rect(0, 0, position.width, position.height), PlayerViewCamera.targetTexture);
}
}

关于c# - 当 Camera.targetTexture = new RenderTexture(...) 时内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53080744/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com