- Home /
RenderTexture causes memory problems
Hi, I have the following code placed in a GUI Window function. I use this to save a RenderTexture rendered by a camera in the "finalRT" variable.
public RenderTexture finalRT;
void NodeWindow(int windowID)
{
RenderTexture heightmapRT = RenderTexture.GetTemporary(1024, 1024, 24, RenderTextureFormat.ARGB32);
GameObject renderCamera = new GameObject();
renderCamera.AddComponent<Camera>();
renderCamera.GetComponent<Camera>().backgroundColor = Color.black;
renderCamera.GetComponent<Camera>().orthographic = true;
renderCamera.GetComponent<Camera>().orthographicSize = 5;
renderCamera.GetComponent<Camera>().transform.localPosition = new Vector3(9999, 10009, 9999);
renderCamera.GetComponent<Camera>().transform.localRotation = Quaternion.Euler(new Vector3(90.0f, 0.0f, 0.0f));
GameObject renderPlane = GameObject.CreatePrimitive(UnityEngine.PrimitiveType.Plane);
renderPlane.transform.localPosition = new Vector3(9999, 9999, 9999);
renderPlane.transform.localRotation = Quaternion.Euler(new Vector3(0, 0, 0));
renderPlane.GetComponent<MeshRenderer>().sharedMaterial.shader = GetNodeByOutput(finalInput.matchedOutput).material.shader;
renderPlane.GetComponent<MeshRenderer>().sharedMaterial.CopyPropertiesFromMaterial(GetNodeByOutput(finalInput.matchedOutput).material);
renderCamera.GetComponent<Camera>().targetTexture = heightmapRT;
renderCamera.GetComponent<Camera>().Render();
RenderTexture.active = heightmapRT;
finalRT = heightmapRT;
renderCamera.GetComponent<Camera>().targetTexture = null;
RenderTexture.active = null;
DestroyImmediate(renderPlane);
DestroyImmediate(renderCamera);
RenderTexture.ReleaseTemporary(heightmapRT);
}
The code works and I'm satisfied with the result, but the system memory is constantly going up. I thought I deleted everything generated at the beginning (renderTexture, camera, plane) so I don't understand. If I remove the clean-up code at the end, memory sky-rockets and causes a crash in seconds, so the clean-up does something. It's just not enough (RAM usage goes up 400K/s).
Does anyone have an idea what the problem would be?
Thanks.
Answer by ScroodgeM · Sep 06, 2012 at 08:20 PM
don't create and destroy objects every call of function. create all needed objects once and use created instances as many times as you need.
btw, GC.Collect() can help in this case, not sure
Answer by cupsster · Jul 15, 2014 at 01:38 PM
Maybe you can squeeze more performance by caching up this call: renderCamera.AddComponent(); into separate value instead of requesting it in each line again and again. This may cause allocations happen I think. And look into Blitz command as well.