In my current project, I’m running into video memory issues (no texture memory available to upload errors) and Unity crashes often.
I do a lot of 2D animations using UnityGUI and static arrays which cycle through when needed. If I create an array of 50 images, does Unity commit all of those images to memory while it is running?
If that’s the case would using a video be any better?
I’m using static arrays that are setup in the editor and loaded with an image sequence. Would it be less memory intensive to create arrays on the fly and Resources.Load images, then trash the array afterwards? Assuming Unity is hanging on to all the images in every array all the time, this method would, theoretically, only worry about arrays that are being rendered?
I use a similar method as you, and I load the textures while the game is running.
You are correct in assuming that editor assigned variables are taking up memory while the game is running.
To semi-correct the problem, you can indeed do as you asked with the Resources.Load in to static arrays, and when not in use, unload them by setting the arrays to null.
to help you, here is my ‘image array loader’ that I wrote.
//loads a sequence of images from Resources folder. Expects images to be numbered from 0001 to (maximum) 9999.
//Returns the image sequence as an array
//filetype doesn't matter, as Resources.Load doesn't take a filetype (you leave it out of the the name)
public static function LoadTexSequence(namePrefix : String, length : int) : Texture[]{
var bars : Texture[] = new Texture[length];
var i=0;
for (i=0;i<length;i++)
{
var j = i + 1;
if (j < 10){
//Debug.Log("loading " + namePrefix + "000" + j);
bars[i] = Resources.Load(namePrefix + "000" + j, Texture);
}
else if (j < 100){
//Debug.Log("loading " + namePrefix + "00" + j);
bars[i] = Resources.Load(namePrefix + "00" + j, Texture);
}
else if (j < 1000){
bars[i] = Resources.Load(namePrefix + "0" + j, Texture);
}
else{
bars[i] = Resources.Load(namePrefix + j, Texture);
}
}
if (bars[0] == null) Debug.LogError("Attempted to load sequence for " + namePrefix + " failed. This is probably due to a bad array prefix");
return bars;
}
How to use:
TexLoader.LoadTexSequence("HUD/quarterCircleValue_", 180);
This will load a texture array starting from image quarterCircleValue_0001 to quarterCircleValue_0180
if you want to make it be zero based, rather than start at one, change the var j = i+1 line to just var j = i, or just change all references of j to i.
Wow, thank you Cerebrate! Not only did you answer my question but you gave me a fancy script to use!