问题
i have a little issue....i want to spawn Quads in my Scene and they all should have either red or green as Material. But the Random.Range function will only int´s, how could i solve it ??
void SpawningSquadsRnd()
{
rndColor[0] = Color.red;
rndColor[1] = Color.green;
for (int i = 0; i < 5; i++)
{
GameObject quad = Instantiate(squadPrefab, new Vector3(Random.Range(- 23, 23), 1.5f, Random.Range(-23, 23)), Quaternion.identity);
int index = Random.Range(0, rndColor.Length);
quad.gameObject.GetComponent<Renderer>().material.color = //Random.Range(0, rndColor.Length);
}
}
回答1:
If you want only red and green you can achieve it with a basic if and else structure like this:
int index = Random.Range(0, 1);
if(index == 1)
{
quad.gameObject.GetComponent<Renderer>().material.color = new Color(1, 0, 0);
}
else
{
quad.gameObject.GetComponent<Renderer>().material.color = new Color(0, 1, 0);
}
If you want something better you can random a float between 0 and 1 and then Lerp between colors like this:
float index = Random.Range(0, 1);
quad.gameObject.GetComponent<Renderer>().material.color = Color.Lerp(Color.red, Color.green, index);
If you want to fully randomized the coloring you can also use this as well. However, it gives you limited amount of control over colors you are getting.
quad.gameObject.GetComponent<Renderer>().material.color = Random.ColorHSV();
ColorHSV
method has several overloads which gives you some control over color like using hueMin
and hueMax
.
Another option to have control over colors can be as @Szymon stated having a color array with plenty of colors and randoming an index between 0 and length of that array.
回答2:
In order to get random color please try :
var randomColor = rndColor[new Random().Next(0,rndColor.Length)]
In that way you will get the random index, and thus the random color from array.
来源:https://stackoverflow.com/questions/54924480/unity-get-random-color-at-spawning