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

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

我想为每一个 "门 "得到一个随机的颜色,所以我有9个门和9种材料和9种颜色,现在我想让每一个门得到一个随机的颜色,但颜色不能重复,例如不能有2个红色或3个蓝色,每个门有一个颜色。enter image description here

下面是我试过的代码,我有2个尝试,旧版本在注释中。

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];
    */
c# unity3d
1个回答
3
投票

在一般情况下,当然假设 material.Length <= colors.Length - 否则就很难实现目标;)

你更想做的是 洗牌 列表,并将它们按 "洗牌顺序 "分配,用 线路 OrderBy

只需将两个数组中的一个数组随机化就可以了

using System.Linq;
using Random = System.Random;
...

public Material[] material;
public Color[] colors;


public void ColorChange()
{
    if(material.Length > colors.Length)
    {
        Debug.LogError("Not enough colors to have a unique color for each material!", this);
        return;
    }

    colors = new [] {
        Color.blue, 
        Color.black, 
        Color.red, 
        Color.green, 
        Color.yellow, 
        Color.white, 
        Color.magenta, 
        Color.cyan, 
        Color.grey };

    var rnd = new Random();
    var randomColors = colors.OrderBy(x => rnd.Next()).ToArray();  

    for(var i = 0; i < material.Length; i++)
    {
        material[i].color = randomColors[i];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.