首页 > 解决方案 > 生成带有颜色的随机按钮

问题描述

我和我的朋友们正在做一个 VR 实验。我们目前有生成 16 个随机颜色按钮的代码,我想要一些代码来重置按钮并再次随机化颜色大约 20 次。我不确定如何处理这种情况。这是我们目前拥有的代码。

    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()
    {
        
    }
}

标签: c#unity3dbuttonvirtual-reality

解决方案


尝试这个:

  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()
   {
    
   }
}

推荐阅读