这是我的代码:
void RandomColor()
{
colors = new[] {
Color.blue,
Color.magenta,
Color.red,
Color.green,
Color.yellow};
int rand = Random.Range(0, colors.Length);
for (int i = 0; i <= colors.Length; i++)
{
PickUp.GetComponent<SpriteRenderer>().color = colors[rand];
}
}
我建议两个选择。第一个是您在分配完项目后从数组中删除项目,以确保没有重复。为此,您需要将颜色设置为列表,以便删除元素。如果要生成5个具有不同颜色的游戏对象,但又不想重复,那么您将需要在函数外部分配一些变量,或者为同一函数中的所有游戏对象设置颜色。在下面的示例中,一个功能用于为所有不同的gameObjects分配随机颜色。
void RandomColor()
{
List<Color> colors = new List<Color>(); // make this list contain the colors you want
while (colors.Count > 0) // will do the following code 5 times if you assign 5 colors to 5 new game objects
{
int rand = Random.Range(0, colors.Length); // get a random color from the lists
GameObject pickUp = Instantiate (PICKUPGAMEOBJECT, WHERE YOU WANT TO SPAWN IT, Quaternion.identity); // Instantiate/spawn your pickup here
pickUp.GetComponent<SpriteRenderer>().color = colors[rand]; // assign the gameObject a random color from the list
colors.Remove (colors[rand]); // remove the item from the list so it can't be called again
}
}
另一种方法是具有另一个数组,并添加您在那里使用过的所有颜色。就像其他示例一样,您将需要使用一个功能为所有不同的gameObjects分配随机颜色。
void RandomColor()
{
Color[] colors = {
Color.blue,
Color.magenta,
Color.red,
Color.green,
Color.yellow};
List<Color> usedColors = new List<Color>();
for (int i = 0; i <= colors.Length; i++)
{
bool foundNewColor = false;
while (!foundNewColor)
{
int rand = Random.Range(0, colors.Length);
if (!usedColors.Contains(colors[rand])
foundNewColor = true;
}
GameObject pickUp = Instantiate (PICKUPGAMEOBJECT, WHERE YOU WANT TO SPAWN IT, Quaternion.identity); // Instantiate/spawn your pickup here
pickUp.GetComponent<SpriteRenderer>().color = colors[rand]; // assign the gameObject a random color from the list
usedColors.Add (color[rand]);
}
}
我尚未测试此代码,但是逻辑已经存在。