0

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 1

2

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Also, make sure that the PNG's import settings is set to Sprite or UI 2D.
thanks, it worked! A follow-up question: Meanwhile, I want to create an array of Strings that contain the names of the PNGs, is there a way to do that?
Check my updated answer. Don't forget to accept if it helped you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.