0

It's me again. You guys have been really amazing and helpful so I was just hoping you'd help me one last time!

What I'm trying to do is to pick a random element from a list when a button is clicked. I know its not the hardest thing to do, but I'm still kinda noob and everything I seem to find its about arrays and I'm not sure an array is the thing to go after, since my list of elements could possibly grow in the future.

So far, I have this code for my listing:

using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

public class FrameSelector : MonoBehaviour
{
    void Start()
    {
            List<bool> frame = new List<bool>();
            frame.Add(GameObject.Find("Frame1").GetComponent<Image>().enabled = true);
            frame.Add(GameObject.Find("Frame2").GetComponent<Image>().enabled = true);
            frame.Add(GameObject.Find("Frame3").GetComponent<Image>().enabled = true);
            frame.Add(GameObject.Find("Frame4").GetComponent<Image>().enabled = true);    
    }

}

The whole point of the random picking, is to show a different image ("Frame") each time the button is pressed.

Thanks!

Valeria Noble
  • 151
  • 1
  • 1
  • 8
  • Possible duplicate of [Access random item in list](https://stackoverflow.com/questions/2019417/access-random-item-in-list) – Rozx Jul 31 '18 at 16:01
  • Can you clarify what list of items you're trying to select randomly from? Right now it looks like you're building a list of boolean values - are those boolean values the items you want to select randomly from? If so, how would you plan on using them once you found one? And where are you handling the click, where you would need to find that random element? – Serlite Jul 31 '18 at 17:47

1 Answers1

0
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI;

public class FrameSelector : MonoBehaviour
{
   List<bool> frame; //make list field not local variable to reuse
   System.Random rand;
   void Start()
   {
        rand = new System.Rand();
        frame = new List<bool>();
        frame.Add(GameObject.Find("Frame1").GetComponent<Image>().enabled = true);
        frame.Add(GameObject.Find("Frame2").GetComponent<Image>().enabled = true);
        frame.Add(GameObject.Find("Frame3").GetComponent<Image>().enabled = true);
        frame.Add(GameObject.Find("Frame4").GetComponent<Image>().enabled = true);    
    }
  void GetRandomObject() // call on click making it public and assigning in inspector 
  {
     int randomNumber = rnd.Next(0,frame.Length-1); //length-1 for not throwing 
//indexError
     //do what you want with your randomNumber
  }

}

You can ask question whenever you want

auslander
  • 470
  • 5
  • 17