In my Unity project, under a canvas, I created a blank UI Image. On the other hand, in the assets folder, I have multiple PNGs. I want the UI Image to be set as a random PNG from the folder via script. How do I do that? Should I attach the script to the UI image or to the UI canvas? Can someone please show me an example script (js, not c#)? Thanks.
1 Answer
Crate a folder named Resources and a subfolder named Sprites. Put your sprites in this folder (images must have the Sprite texture type in the image import settings, as pointed out by @SurajS).
Create an image element and attach the following UnityScript to it :
function Start () {
var image : UnityEngine.UI.Image = GetComponent.<UnityEngine.UI.Image>();
var sprites : Object[] = Resources.LoadAll("Sprites", Sprite);
image.sprite = sprites[Random.Range(0, sprites.Length)] as Sprite;
}
Better solution (more efficient)
Attach the following script to the gameobject you want (your image, your canvas or even an empty)
#pragma strict
public var image : UnityEngine.UI.Image;
public var sprites : Sprite[];
function Start () {
image.sprite = sprites[Random.Range(0, sprites.Length)] ;
}
Then, in the inspector, drag & drop the gameobject holding your image component in the image field, and put all the sprites you want in the sprites field.
To get the name of the sprites, you can do as follow :
var names : String[] = new String[sprites.Length] ;
for (var i = 0 ; i < names.Length ; ++i ) {
names[i] = sprites[i].name;
}