- Home /
Question by
nibek1000 · Nov 25, 2017 at 08:39 PM ·
spriterandomimagerandom.range
List and random Sprites?
Hi there, Im new in Unity and Im stuck at makeing lists of Sprites. I want to show random Sprite and load this level again, to show random Sprite again. Here what I made for now.
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class ChangeImage : MonoBehaviour
{
public Sprite OtherSprite;
public Sprite OtherSprite1;
public int number = 1;
Image[] images;
void Start()
{
number = Random.Range(1, 3);
images = gameObject.GetComponentsInChildren<Image>();
foreach (Image image in images)
{
StartCoroutine(Count());
//image.sprite = OtherSprite;
}
}
IEnumerator Count()
{
foreach (Image image in images)
{
image.sprite = OtherSprite;
if (number == 1)
{
image.sprite = OtherSprite;
}else if (number == 2)
{
image.sprite = OtherSprite1;
}
yield return new WaitForSeconds(2);
Application.LoadLevel(0);
}
}
}
I was trying to use random number to get random Sprites by If Any help?
Comment
Best Answer
Answer by Reynarz · Nov 25, 2017 at 10:22 PM
Maybe this is what you want...
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class ChangeImage : MonoBehaviour
{
public Sprite[] _myOthersSprites;
private Image[] _images;
void Start()
{
_images = gameObject.GetComponentsInChildren<Image>();
StartCoroutine(Count());
}
IEnumerator Count()
{
for(int i = 0; i < _images.Length; i++)
{
var spriteNumber = Random.Range(0, _myOthersSprites.Length - 1);
_images[i].sprite = _myOtherSprites[spriteNumber];
}
yield return new WaitForSeconds(2);
Application.LoadLevel(0);
}
}
i just copy pasate it but it says
The name '_myOtherSprites' does not exist in the current context
There's a typo here _images[i].sprite = _myOtherSprites[spriteNumber];
, it should be _images[i].sprite = _myOthersSprites[spriteNumber];
Your answer
![](https://koobas.hobune.stream/wayback/20220612143336im_/https://answers.unity.com/themes/thub/images/avi.jpg)