简体   繁体   中英

Generating random button with colors

my friends and I are working on a VR experiment. We currently have code that generates 16 buttons with randomized colors, I would like to have some code that resets the buttons and randomizes the color once again for about 20 times. I'm unsure how to approach the situation. Here is the code we currently have.

    public class ButtonManager : MonoBehaviour
{
    Text[] labels;
    Image[] images;
    // Start is called before the first frame update
    Color[] colors = new Color[]{
        Color.red,Color.green,Color.yellow,Color.magenta,Color.gray,Color.black
    };
    void Start()
    {
        int chosenOne = Random.Range(0, 16);
        Debug.Log(chosenOne.ToString());
        labels = gameObject.GetComponentsInChildren<Text>();
        int elemNum = 0;
        foreach (Text txt in labels)
        {
            txt.text = elemNum.ToString();
            elemNum++;
        }
        images = gameObject.GetComponentsInChildren<Image>();
        elemNum = 0;
        foreach (Image btn in images)
        {
            if (elemNum == chosenOne + 1)
            {
                btn.color = Color.blue;
            }
            else
            {
                btn.color = colors[Random.Range(0, 6)];
            }
            elemNum++;
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

Try this:

  public class ButtonManager : MonoBehaviour
  {
    Text[] labels;
    Image[] images;
    // Start is called before the first frame update
    Color[] colors = new Color[]{
    Color.red,Color.green,Color.yellow,Color.magenta,Color.gray,Color.black
    };
    void Start()
    {
    labels = gameObject.GetComponentsInChildren<Text>();
    foreach (Text txt in labels)
    {
        txt.text = elemNum.ToString();
        elemNum++;
    }
    images = gameObject.GetComponentsInChildren<Image>();
    foreach (Image btn in images)
    {
       btn.color = colors[Random.Range(0, colors.Length)];
    }
   }

   // Update is called once per frame
   void Update()
   {
    
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM