Hello, so i wrote this
var colors : Color[] = new Color[4];
function RandomColorBegining()
{
GetComponent(SpriteRenderer).color = colors[Random.Range(0,2,3)];
}
The only thing i want to do is to make random color exluding [1], exluding colors[1];
But i dont know how to i tried researching on google but couldnt find anything could anyone help me :?
Thanks!
This is one of those things where there are a bunch of algorithms to accomplish what you want, and they’re all very different. Many of these algorithms would require looping through the array, or rebuilding the array to exclude the one you don’t want, or something. Here’s one way - I like this one because it’ll be more efficient than rebuilding the array.
function RandomColorExcluding(exclude : int) {
var rndIndex = Random.Range(0, colors.Length - 1);
if (rndIndex >= exclude) rndIndex++;
GetComponent(SpriteRenderer).color = colors[rndIndex];
}
1 Like
Hi there, thanks for reply but i dont really get this code so i have no idea how to put it into my code could you please make comments on each line what do they mean.
I tried putting it in my code ‘blindly’ as i dont understand it well and i got this error ‘‘The best overload for the method ‘RandomColorPlayer.RandomColorBegining(int)’ is not compatible with the argument list ‘()’.’’
this is what i have in code
function Start()
{
colors[0] = Color.blue;
colors[1] = Color.red;
colors[2] = Color.green;
colors[3] = Color.yellow;
//colors[3] = new Color(255, 165, 0);
RandomColorBegining();
}
function RandomColorBegining(exclude : int)
{
var rndIndex = Random.Range(0, colors.Length - 1);
if (rndIndex >= exclude) rndIndex++;
GetComponent(SpriteRenderer).color = colors[rndIndex];
}
Hi there, looks like it works i just stared at this code for like 30 min and tried to mix it and change it so basically i removed from function ‘‘exclude : int’’ and where if >= exclude i replaced with the number i wanna exclude.
So yeah it works now
thanks !
Nice task.
Let me solve it in C# (i know, you already have a solution, but I maybe someday somebody needs it):
public static T PickRandom<T>(params T[] elements)
{
UnityEngine.Asserts.Assert.IsTrue(elements.Length > 0, "PickRandom: You must pass at least one element.");
int idx = UnityEngine.Random.Range(0, elements.Length);
return elements[idx];
}
and this is how to use it:
int index = PickRandom<int>(0, 2, 3);
// C# is super smart so you can also write:
int index = PickRandom(0, 2, 3);
1 Like