Page 1 of 1

Help with some code

PostPosted: 27 Oct 2013, 00:21
by leftearbud
Hello,

so I have made an array to store some things

Code: Select all
ArrayList messages = new ArrayList();
            //add the messages
            messages.Add("Message1");
            messages.Add("Message2");
            messages.Add("Message3");


and then I use

Code: Select all
int r = rnd.Next(messages.Count);


to randomly get one of the messages and then I send a player the randomly selected message

Code: Select all
Player.SendMessage(p, (string)messages[r]);


and that all works fine but now I have a need to send all the players on the server one of those randomly selected messages and I can't work out how I would send a different message to every player. I have been able to send all the players on the server the same message just not a different message to each individual player.

Any help on this is greatly appreciated

Re: Help with some code

PostPosted: 27 Oct 2013, 00:33
by dzienny
You have to generate a new random number for each player. It means you have to generate the number within a loop. For example:
Code: Select all
Random rnd = new Random();
Player.players.ForEachSync(p =>
{
    Player.SendMessage(p, (string)messages[rnd.Next(messages.Count)]);
});


By the way, instead of ArrayList you are better off using List<String>. It's type safe and it doesn't require casting.

Re: Help with some code

PostPosted: 27 Oct 2013, 01:56
by leftearbud
dzienny wrote:You have to generate a new random number for each player. It means you have to generate the number within a loop. For example:
Code: Select all
Random rnd = new Random();
Player.players.ForEachSync(p =>
{
    Player.SendMessage(p, (string)messages[rnd.Next(messages.Count)]);
});


By the way, instead of ArrayList you are better off using List<String>. It's type safe and it doesn't require casting.



Thanks a lot I got it working. I'll also take a look into List<String> thanks for the advice.