Help with some code

Help with some code

Postby leftearbud » 27 Oct 2013, 00:21

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
leftearbud
 
Posts: 2
Joined: 27 Oct 2013, 00:00

Re: Help with some code

Postby dzienny » 27 Oct 2013, 00:33

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.
User avatar
dzienny
Administrator
 
Posts: 1181
Joined: 23 Jan 2011, 14:27

Re: Help with some code

Postby leftearbud » 27 Oct 2013, 01:56

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.
leftearbud
 
Posts: 2
Joined: 27 Oct 2013, 00:00


Return to Help in Coding

Who is online

Users browsing this forum: No registered users and 3 guests

cron