Search Unity

Random sprite selector

Discussion in 'Scripting' started by petizero, Sep 14, 2019.

  1. petizero

    petizero

    Joined:
    Jan 1, 2019
    Posts:
    47
    Hi i would like to implement a system that chooses a random sprite each time the game is started (just messing around with random generation at the moment)

    So the way i'd like this to work is that there is an empty game object with a sprite renderer in it which chooses a random sprite
    the hard part is that i have no clue how to create a selection of sprites for the script

    any help?
     
    PentaPenta23 likes this.
  2. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    The general approach would look something like this:
    • Have an array or a list of all sprites
    • Generate a random index between 0 and spriteList.Count
    • Use the sprite at spriteList[randomIndex] as the sprite that gets rendered
    Attach the script that does the above to your gameobject with the sprite renderer. In the Start() method use GetComponent to get the reference to the sprite renderer. After you selected the right sprite, make the sprite renderer render it. You dont need Update(), so everything happens in start. Reference sprite renderer -> select random sprite -> make renderer render the sprite.
     
  3. petizero

    petizero

    Joined:
    Jan 1, 2019
    Posts:
    47
    How di i create a sprite list though?
     
  4. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    Either load it from somewhere, or assign all sprites you want to chose from through the inspector.
     
  5. petizero

    petizero

    Joined:
    Jan 1, 2019
    Posts:
    47
    So make a prefab with all the sprites ?
     
  6. Yoreki

    Yoreki

    Joined:
    Apr 10, 2019
    Posts:
    2,605
    When you put a "[SerielizeField] private List<Sprite> spriteList" into your script, you could then fill the list from the inspector. I never worked with sprites, so i dont actually know if "Sprite" is a type that even exists, but you probably know which type to reference, so yeah.
     
  7. petizero

    petizero

    Joined:
    Jan 1, 2019
    Posts:
    47
    All right i have been thinking how to do this but i finally finished and its glorius thanks for the help my dude