0

I am creating an unity project which I will attach to my web. As it is on my web I am trying to optimize my code as much as I know or know how to ask about it. I don't know if all variables created in method are destroyed/deleted then program finishes the method.

For example I have this method:

Texture2D TakePhoto()
{
    var currentRT = RenderTexture.active;
    RenderTexture.active = photoCamera.targetTexture;
    photoCamera.Render();
    Texture2D image = new Texture2D(photoCamera.targetTexture.width, photoCamera.targetTexture.height);
    image.ReadPixels(new Rect(0, 0, photoCamera.targetTexture.width, photoCamera.targetTexture.height), 0, 0);
    image.Apply();
    RenderTexture.active = currentRT;
    return image;
}

Should I destroy 'currentRT' object manually in the end of the method? Or will it be destroyed automatically? I don't want this kind of information to float around needlessly. Also does it work the same with basic variables: ints, strings, chars and so?

Marsd3q
  • 60
  • 6

1 Answers1

2

Unity does not automatically garbage collect Texture2D, as seen here, meaning you should call Destroy() on it at the end of usage.

In this case, though, you should probably instantiate it by reference, to prevent wasting memory, as you can't destroy at the end since you're returning it.

Here's a fixed method:

Texture2D TakePhoto(ref Texture2D tex)
{
    var currentRT = RenderTexture.active;
    RenderTexture.active = photoCamera.targetTexture;
    photoCamera.Render();
    tex = new Texture2D(photoCamera.targetTexture.width, photoCamera.targetTexture.height);
    tex.ReadPixels(new Rect(0, 0, photoCamera.targetTexture.width, photoCamera.targetTexture.height), 0, 0);
    tex.Apply();
    RenderTexture.active = currentRT;
}
Larry Tang
  • 642
  • 5
  • 23