- Home /
How do you script to show random image for seconds?
To the point, i hope there's good people outside. Just say i have 5 or 10 pictures and i want it show randomly in random time for 1 second? How do you do that?
Comment
Answer by Cherno · Mar 17, 2017 at 04:00 PM
using UnityEngine.UI;
public float time_min = 1f;
public float time_max = 3f;
public Sprite[] sprites = new Sprite[0];
public Image image;
void Start() {
StartCoroutine("ShowRandomImage");
}
public IEnumerator ShowRandomImage() {
while(true) {
image.sprite = sprites[Random.Range(0, sprites .Length)];
image.enabled = true;
yield return new WaitForSeconds(1);
image.enabled = false;
yield return new WaitForSeconds(Random.Range(time_min, time_max));
}
}
Answer by toddisarockstar · Mar 17, 2017 at 05:15 PM
// you must drag and drop images into all the blanks in the inspector!!!
public Texture2D pic0;
public Texture2D pic1;
public Texture2D pic2;
public Texture2D pic3;
public Texture2D pic4;
public int pick;
Texture2D[] pics;
int i;
float timer;
void Start () {
//pack images into an array to make things easy
pics = new Texture2D[5];
pics [0] = pic0;
pics [1] = pic1;
pics [2] = pic2;
pics [3] = pic3;
pics [4] = pic4;
}
void Update () {
timer -= Time.deltaTime;
if (timer < 0) {timer = 2.5f;//<--this happens about every second;
//get a random number not equal to current
i=pick;
while(i==pick){
pick=Random.Range(0,5);}
}
}
void OnGUI(){
//display our image
GUI.DrawTexture (new Rect (50, 50, 300, 300), pics [pick]);
}