c# - 生成带有颜色的随机按钮
问题描述
我和我的朋友们正在做一个 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()
{
}
}
解决方案
尝试这个:
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()
{
}
}
推荐阅读
- python - 如何在张量流数据集中映射numpy数组
- arrays - 循环遍历数组并写入错误消息
- python - 使用 python sqlalchemy 使用 WITH 语句执行原始查询
- javascript - 当作为子组件添加时,以不同的方式对本机组件渲染做出反应
- spring-boot - Kafka 消费者的 Spring Boot/Jhipster 集成测试构建失败
- sql-server - 之前用?分配查询结果?
- python - Tensorflow/Keras Conv2D 层中的输入形状错误
- qt - qt.qpa.plugin:无法在“”中加载 Qt 平台插件“xcb”,即使它已找到
- html - 嘿,我有一个图像横幅,在循环中向左移动,但我想在悬停时为这些图像添加文本。谢谢
- r - 使用 R 中的邮政编码在美国创建自定义销售区域