I have many image in folder screenshots. So this script will be calling the image from folder without applying. But the thing is, the image only displays one image. I mean they did not go to next image like slide show or fade in/out.
Then I keep getting this error message:
IndexOutOfRangeException: Index was outside the bounds of the array.
It points to this code:
ImageHolder[i].GetComponent<RawImage>().texture = thisTexture;
Full code:
Texture2D thisTexture;
byte[] bytes;
string fileName;
public GameObject[] ImageHolder = new GameObject[1];
void Start()
{
var imagesToLoad = Directory.GetFiles(Application.dataPath "/screenshots", "*.png");
for (int i = 0; i < imagesToLoad.Length; i )
{
thisTexture = new Texture2D(100, 100); //NOW INSIDE THE FOR LOOP
fileName = imagesToLoad[i];
bytes = File.ReadAllBytes(fileName);
thisTexture.LoadImage(bytes);
thisTexture.name = fileName;
// This line
ImageHolder[i].GetComponent<RawImage>().texture = thisTexture;
}
}
}
Here I attached the output. I have 4 RawImage
's. The image just displays and gets stuck.
CodePudding user response:
Update!! the error was solved!
I put the variable at image holder
from this
*ImageHolder[i].GetComponent<RawImage>().texture = thisTexture;
to
*ImageHolder[9].GetComponent<RawImage>().texture = thisTexture;
but only display at RawImage(9) and still stuck with one image.
CodePudding user response:
As I understood you fill the array ImageHolder with GameObjects in the Editor. Hence you could remove the not relevant and confusing assignment of new GameObject[1] when you initalize the field.
But you should break out of the for loop if your ImageHolder array is shorter than imagesToLoad array.
Or account for it differently by expanding the array and creating new ImageHolders GameObject in which case you probably want to use a list. You could directly reference the RawImage and create a Prefab so you can create and fill your list more easily.
Instead of breaking out of the for loop you could just resize the imagesToLoad array or if you want to use the first use .First() or a select a specific range.