The following class is some C# code I saw posted and modified. As a test I want to be able to load the same image file every frame and reload a mesh object material’s texture with it. This code causes Unity to crash because it consumes and does not seem to release memory. In C++ I’d call delete on the pointer or use a smart ptr. In C# I’m not sure how to remedy? Here’s the code:
using System.IO;
using UnityEngine;
public class LoadTexture : MonoBehaviour {
public Texture2D LoadTextureFromFile(string filename)
{
Texture2D texture = new Texture2D(2048, 2048);
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
byte[] imageData = new byte[fs.Length];
fs.Read(imageData, 0, (int)fs.Length);
texture.LoadImage(imageData);
return texture;
}
void Update() {
renderer.material.mainTexture = LoadTextureFromFile("C:\\Users\\bhart\\Pictures\\Mactexture.png");
}
}
Note the original code I borrowed had:
public static Texture2D LoadTextureFromFile(string filename)
I’m not sure what the static does in this case, but unity crashes with or without it.