- Home /
Unity4 problem - Bypassing camera renderTexture with ReadPixels but system out of memory
I made a game in Unity 4 Pro and it doesn't seem to be running in Unity 5 so I want to keep working in Unity 4. The problem is the pro trial expired and therefore I no longer have the render texture to camera feature. So I'm trying to bypass this issue by using ReadPixels instead.
What I need to do is to create a render of couple of layers from a camera and apply it as a texture onto an object over a period of time. Just to give a bit more context, it's a hinting mechanism for this point and click game, when you go over the scene with this magnifying glass, the magnifying glass displays highlighted objects that you can interact with. I have it sort of working. It takes screenshots of the layers over a period of time and displays it on the magnifying glass but then the memory runs out and Unity crashes saying:
"Fatal error! Could not allocate memory; System out of memory!... "
As you'll see in the code, I'm trying to release or reset the grabTexture because I believe this is what is causing the problem but I'm not sure of the proper way to do this.
using UnityEngine;
using System.Collections;
public class CameraGrabScript : MonoBehaviour
{
public bool grab = true;
//public Texture2D grabTexture;
public Renderer magglass;
private void OnPostRender()
{
if(grab)
{
Debug.Log("Grabbing");
Texture2D grabTexture = new Texture2D(Screen.width, Screen.height);
grabTexture.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
grabTexture.Apply();// mip maps
magglass.material.mainTexture = grabTexture;
grabTexture = null;
//Resources.UnloadAsset(grabTexture); //function can only be called on Assets that are stored on disk.
//Destroy(grabTexture);
//grab = false;
Debug.Log("grabTexture is null");
}
}
}
Thank you for your help.
not sure where your error is, i just don't get why you null that grabTexture ... it's reference, so if you null it you null also the mainTexture on material
and also, you should uncomment the grab = false; (that might make the memory leak)
and if you are trying to do it every frame ... then just forget it and use render texture
Answer by hu90 · May 28, 2015 at 07:38 PM
You are allocating a new Texture every frame, with the size of the screen. Even if the garbage collector could keep up with this, it's terrible.
You should instantiate a texture the size of the screen just once instead of OnPostRender (then ReadPixels on it OnPostRender if you want).
But my advice in your case would be to upgrade to Unity 5, all the engines features are free. Upgrading your project will likely take minutes and you'll save yourself some headaches.