- Home /
Using an IEnumerator to return another type of variable
Hi! Eh my first question for the unity community :)
So!...
I wanted to make a script to load all the .jpg files in a folder into a Texture2D[] to use it to populate the objects in my game.
I did it with an Ienumerator type function and a coroutine (dont understand that much about them :( ). Started out with a simple Ienumerator on one script, which places the texture into a global variable... But now i wanted to make this function global so i could call in every other script. So i wanted the IEnumarator function to return a Texture[] variable..
So far i got to this:
public IEnumerator LoadImages(string[] f,string pathFolder, System.Action < Texture2D[]> result){
text1 = new Texture2D[f.Length];
int dummy = 0;
foreach(string tstring in f){
string pathImage = pathFolder + tstring;
WWW www = new WWW(pathImage);
yield return www;
Texture2D texTmp = new Texture2D(1024, 1024, TextureFormat.DXT1, false);
www.LoadImageIntoTexture(texTmp);
text1[dummy] = texTmp ;
dummy++;
}
result(text1);
}
and call it like this:
void Awake(){
string path = @"D:\Projects\Kinect Sign\Assets\contos";
pathPreFix = @"file://";
subPath = System.IO.Directory.GetDirectories(path);
foreach(string element in subPath){
files = System.IO.Directory.GetFiles( element, "*.jpg");
StartCoroutine(LoadImages(files,pathPreFix,(x) => textList = x));
}
}
If i call it in my main script it kinda works... But on everyother script it just says: "NullReferenceException: Object reference not set to an instance of an object"
Not that sure on whats happening...
Answer by Slobdell · Apr 01, 2014 at 06:36 PM
you don't want to use absolute paths because they won't exist when you deploy to whatever device. The general strategy is to create a folder called Resources in your assets folder. Then put all your images in there or create an images folder within there. Then, in your case you could call Resources.LoadAll("path within resources I.e. Images". This method will return an object array of all the files which you can cast to 2d texture array and don't even need your function
Hum yes you do have a point there... and i ended goin to that solution, cause i had already tried the Resources.Loadxxxx but it didnt seem to work.. So i create a Resources/Images/folderX and can use it
Texture2D[] textList = Resources.LoadAssetAtPath(Resources/Images/folderX, jpg)
something like this? gonna try it out as soon as i get home thxs ^^
Yes mostly right, that may work but I would do this. Create folder Resources/Images/folderX and then
Texture2D[] textList = Resources.LoadAll("Images/folderX"),
Well tried to use resources.loadall() and i keep getting a "NullReferenceException: Object reference not set to an instance of an object" on every way i try to use it.. :(
edit: even the unity reference manual gives me the same error...
Your answer
![](https://koobas.hobune.stream/wayback/20220613141710im_/https://answers.unity.com/themes/thub/images/avi.jpg)