Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Random Sprite from Folder

Discussion in 'Scripting' started by ElnuDev, Apr 30, 2018.

  1. ElnuDev

    ElnuDev

    Joined:
    Sep 24, 2017
    Posts:
    298
    I want to choose a random Sprite from a folder and set it to the Sprite component of an UI Image. This is my code so far:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class RandomPhotoPicker : MonoBehaviour {
    7.  
    8.     public Sprite[] photos;
    9.     private Image imageComponent;
    10.  
    11.     // Use this for initialization
    12.     void Start () {
    13.         imageComponent = GetComponent<Image> ();
    14.         imageComponent.sprite = photos [Random.Range (0, photos.Length)];
    15.     }
    16. }
    17.  
     
  2. mgear

    mgear

    Joined:
    Aug 3, 2010
    Posts:
    9,350
    would those images be placed there at runtime? (external folder, where user can place new images anytime?)
     
    ElnuDev likes this.
  3. Miggi124

    Miggi124

    Joined:
    Jul 31, 2017
    Posts:
    69
    Hi,

    Shouldn't this solution already work? If you are trying to retrieve assets from a folder in your assets, try looking through this video. It should help.



    -Miggi124
     
    ElnuDev likes this.