简体   繁体   中英

How do I make my code perform a random function

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?

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM