【问题标题】:Generating random button with colors生成带有颜色的随机按钮
【发布时间】:2021-12-11 07:25:42
【问题描述】:

我和我的朋友正在做一个 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()
    {
        
    }
}

【问题讨论】:

  • 我建议你把按钮的创建逻辑和颜色设置逻辑分成两个不同的方法,这样你就可以从Start()调用CreateButtons()方法只创建一次按钮,也可以立即调用@987654324 @ 来自Start(),然后您可以随时再次调用SetColors(),并重复使用按钮,而不是每次都破坏它们并重新创建它们。

标签: c# unity3d button virtual-reality


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-07
    • 2012-02-19
    • 2013-04-02
    • 2018-04-02
    • 2021-05-23
    • 2011-03-09
    • 1970-01-01
    相关资源
    最近更新 更多