views:

107

answers:

2

I want my code to randomize between three different functions:

private void BackPack1()
{
    Player.Skin.SetComponent((PedComponent)3, 3, 0);
}

private void BackPack2()
{
    Player.Skin.SetComponent((PedComponent)3, 3, 1);
}

private void BackPack3()
{
    Player.Skin.SetComponent((PedComponent)3, 3, 2);
}

Is there an easy way?

+5  A: 
private static Random r = new Random();

private void BackPack() {
    int i = r.Next(0,3);
    Player.Skin.SetComponent((PedComponent)3, 3, i); 
}

Only the last argument of your method call changed, so I assumed you wanted to randomize that argument.

pb
Why make the Random object static? The empty constructor will seed it with a time-based value anyway. </NITPICK>
MusiGenesis
To ensure that two objects generated at the same time, will not generate the same 'random' values.And it's cheaper.
pb
In this context, who cares if two objects generate the same values? You only have three possibilities anyway.
MusiGenesis
Sorry, I'm bored. :)
MusiGenesis
There's always the change that this code is used in a piece of code and changed to support more possibilites. This way that scenario will work better.
pb
In the greater scheme of things, makes zero difference either way.
Ray Booysen
+3  A: 

This code randomly calls one of the BackPack*X* functions

Action[] methods = new Action[] { BackPack1, BackPack2, BackPack3 };
Random rnd = new Random();
int index = rnd.Next(3);
Action method = methods[index];
method();
Thomas Levesque