There is a code

public void SetTeam(Player player) { foreach (Team team in Teams.ToArray()) { if (team.IsFull()) { continue; } else { if (!team.InCommand(player)) { team.AddPlayer(player); } break; } } } 

With this code, I fill in the teams with players, there are only two of them, 1 or 2 players, depending on the mode. So I distribute:

 foreach (Player player in GetPlayers().ToArray()) { SetTeam(player); Prespawn(player); TeleportToTeamSpawn(player); } 

But it happens that the players distribute incorrectly, it happens that one player throws in different teams. Distribution is carried out in a timer.

Team.cs

 public class Team { public string Name { get; set; } = "0"; public int MaxPlayers { get; set; } = 0; public bool IsEliminated { get; set; } = false; public Vector3 Spawn { get; set; } = Vector3.Zero; public Vector3 Portal { get; set; } = Vector3.Zero; public int Points { get; set; } = 0; public List<Player> Players = new List<Player>(); public Team(int maxplayers, string name) { MaxPlayers = maxplayers; Name = name; } public void AddPlayer(Player player) { if (IsFull()) return; if (!Players.Contains(player)) { Players.Add(player); } } public void RemovePlayer(Player player) { if (Players.Contains(player)) { Players.Remove(player); } } public bool IsFull() { if (Players.Count == MaxPlayers) { return true; } return false; } public void Reset() { IsEliminated = false; Points = 0; Players.Clear(); Players = null; Players = new List<Player>(); } public bool InCommand(Player player) { if (Players.Find((x) => x.Username.ToLower() == player.Username.ToLower()) is Player) { return true; } return false; } } 

There is a guess that this is due to different threads.

  • one
    Very badly asked. "Distribution is on timer." - Do you think everything became clear to us? This phrase gives rise to the worst suspicions. - Igor
  • The timer that calls this function - Kirill Meøw pm
  • one
    I'll give you a minus for this explanation now. - Igor
  • Your questions (this and the previous one about the flag with a delay) are very similar to each other. You do not give us a general picture, but tear out pieces of code with a minimal explanation of which algorithm you want to implement. It's like asking your subscribers on instagram, showing them photos taken on a mobile phone through the porthole, whether the yacht is going in the right direction or the plane is flying. - Bulson 6:54 pm
  • and what is not clear here? - Kirill Meøw 7:05 pm

1 answer 1

I think the guess is correct. The List<T> class has the SyncRoot property SyncRoot Try to rewrite all your calls to the collection methods as follows ...

 lock (Players.SyncRoot) { // Access the collection. }