Is it possible to use Resources.Load() to load an entire subfolder?
I'm a unity newbie, so I'm sorry if this really easy. I'm just having trouble finding examples online of this.
I have a subfolder within the Resources folder. This subfolder contains several images that I would like to load. The number of images within this folder will not always be the same, so I don't just want to hard code loading in each image separately, because I don't know how many there will be. Is it possible to load the entire subfolder at once and save it to an array? I tried the below code and it throws errors. Any suggestions?
The images are in Assets/Resources/Images/
Texture[] images = Resources.Load("Images/", typeof(Texture)) as Texture;
Answer by TBruce · Apr 16, 2016 at 08:00 PM
@ eclaire211
Try
Texture[] images = Resources.LoadAll("Images", typeof(Texture));
or if you would rather use a List
using System.Collections.Generic;
List<Texture> images = new List<Texture>(Resources.LoadAll("Images", typeof(Texture)));
Note, depending on your needs, you may want to use Texture2D instead of Texture.
@$$anonymous$$avina Thank you for your answer! However, I'm still having an issue. I just tried:
Texture[] images = Resources.LoadAll("Images", typeof(Texture)) as Texture[];
(I added in the "as Texture[]" because it was throwing errors without it)
When I try to access the images array, I get a NullReferenceException. Do you know why my array is null?
$$anonymous$$y bad, do this ins$$anonymous$$d
Object[] objects = Resources.LoadAll("Textures", typeof(Texture));
Texture[] images;
if (objects != null)
{
images = new Texture[objects.Length];
for (int i = 0; i < objects.Length; i++)
{
images[i] = (Texture)objects[i];
}
Debug.Log("images.Length " + images.Length);
}
or if using a List
using System.Collections.Generic;
Object[] objects = Resources.LoadAll("Textures", typeof(Texture));
List<Texture> images = new List<Texture>();
if (objects != null)
{
images = new Texture[objects.Length];
for (int i = 0; i < objects.Length; i++)
{
images.Add((Texture)objects[i]);
}
Debug.Log("images.Length " + images.Length);
}
@$$anonymous$$avina Thank you so much! This fixed the problem! :)
You can also do it this way (I haven't tried with lists or Texture specifically):
using System.Linq;
Texture[] images = Resources.LoadAll("Images", typeof(Texture)).Cast<Texture>().ToArray();