I have this script to capture an image from a camera and transfer that image to a sprite in runtime. However, it slowly uses up all my computer’s memory until it crashes. I’m not sure what’s up with that. Can anyone help?
public class RenderTextureImage : MonoBehaviour {
public int height = 128;
public int width = 128;
public GameObject updateMe;
public float framesPerSecond = 10;
RenderTexture tempRT;
Texture2D virtualPhoto;
byte[] bytes;
Sprite sprite;
// Use this for initialization
void Start () {
StartCoroutine(drawImage());
}
// Update is called once per frame
IEnumerator drawImage() {
while(true){
tempRT = new RenderTexture (width, height, 24);
GetComponent<Camera>().targetTexture = tempRT;
GetComponent<Camera>().Render();
RenderTexture.active = tempRT;
virtualPhoto = new Texture2D (width, height, TextureFormat.ARGB32, false);
virtualPhoto.ReadPixels (new Rect (0, 0, width, height), 0, 0);
bytes = virtualPhoto.EncodeToPNG ();
virtualPhoto.LoadImage(bytes);
sprite = Sprite.Create(virtualPhoto, new Rect(0,0, width, height), new Vector2(0.5f, 0.5f));
updateMe.GetComponent<SpriteRenderer>().sprite = sprite;
yield return new WaitForSeconds(1/framesPerSecond);
}
}