如何获得不重复的随机颜色?

问题描述 投票:0回答:1

我想为每个,, gate添加一个随机的颜色。所以我有9个gate和9种材质和9种颜色。现在,我希望每个gate都获得随机的颜色,但是颜色不能重复。例如,可以不是2种红色或3种蓝色,每种一种。感谢您的帮助enter image description here

这里是我尝试过的代码。我有2次尝试。旧版本在注目中

enter image description here
c# unity3d
1个回答
3
投票

[通常当然假设public Material[] material; public Color[] colors; public void ColorChange() { colors[0] = Color.blue; colors[1] = Color.black; colors[2] = Color.red; colors[3] = Color.green; colors[4] = Color.yellow; colors[5] = Color.white; colors[6] = Color.magenta; colors[7] = Color.cyan; colors[8] = Color.grey; int randomcolor = Random.Range(0, colors.Length); int randommaterial = Random.Range(0, material.Length); material[randommaterial].color = colors[randomcolor]; material[randommaterial].color = colors[randomcolor]; material[randommaterial].color = colors[randomcolor]; material[randommaterial].color = colors[randomcolor]; material[randommaterial].color = colors[randomcolor]; material[randommaterial].color = colors[randomcolor]; material[randommaterial].color = colors[randomcolor]; material[randommaterial].color = colors[randomcolor]; material[randommaterial].color = colors[randomcolor]; /*int color1 = Random.Range(0, colors.Length); int color2 = Random.Range(0, colors.Length); int color3 = Random.Range(0, colors.Length); int color4 = Random.Range(0, colors.Length); int color5 = Random.Range(0, colors.Length); int color6 = Random.Range(0, colors.Length); int color7 = Random.Range(0, colors.Length); int color8 = Random.Range(0, colors.Length); int color9 = Random.Range(0, colors.Length); material[0].color = colors[color1]; material[1].color = colors[color2]; material[2].color = colors[color3]; material[3].color = colors[color4]; material[4].color = colors[color5]; material[5].color = colors[color6]; material[6].color = colors[color7]; material[7].color = colors[color8]; material[8].color = colors[color9]; */ -否则将难以实现目标;)

您想做的是shuffle您的列表,并使用material.Length <= colors.Length以“随机排序”分配它们>

足以随机化两个数组之一

Linq OrderBy    
© www.soinside.com 2019 - 2024. All rights reserved.