Hello all,
I have two classes, team and player.
I currently instantiate an array of team objects within the unity inspector, and within each of those is an array of players.
My problem is that I need to understand which team a particular player belongs to. I’ve tried:
-
Looping through the array of team objects to find the player name, the drawback is that two teams could have a player with the same name. Giving each player a unique ID would solve this, but I don’t know if it’s the best solution.
-
Referencing the team object within the player object, which seems like bad practice, and if I wanted to make it publicly accessible it would interfere with the serialization property I gave to the player object for it to show in the unity inspector.
Thanks for any help.
Your player objects already have unique IDs. Just give your Team a List or HashSet. Then you can have a method like this:
List<Player> players = new List<Player>();
bool ContainsPlayer(Player p) {
return players.Contains(p);
}
By default this will check each player for reference equality with p
.
If you want to get really fancy, you can store a separate Dictionary somewhere with Player → Team mappings:
Dictionary<Player, Team> teamMappings = new Dictionary<Player, Team>();
void AddPlayerToTeam(Player p, Team t) {
teamMappings[p] = t;
}
Team GetTeamOfPlayer(Player p) {
if (teamMappings.TryGetValue(p, out Team t) {
return t;
}
return null;
}
You would have to make sure this stays in sync with all of the teams’ player arrays.
Finally, if you want to stick with Arrays, as long as your teams have arrays of Player objects, you can use Array.indexOf to find the index of that player in a team: Array.IndexOf Method (System) | Microsoft Learn
Team findTeamContainingPlayer(Player p) {
foreach (Team team in teams) {
int playerIndex = team.players.indexOf(p);
if (playerIndex > -1) {
return team;
}
}
return null;
}
Thanks for the informative reply.
Solves the problem and I will be converting to a list.
Much appreciated.