- Home /
How to make a dynamic list of a serializable variable?
Hi everyone,
I am new with serializable variables and I got a problem that is probably trivial. I have a serializable variable (here "player") with 2 components (name and class) and during the character selection I need to add the class selected to a allPlayer list.
Here is the serializable player
[System.Serializable]
public class Player
{
public string name;
public TacticsActions.Classes playerClass;
public Player(Player d)
{
name = d.name;
playerClass = d.playerClass;
}
}
And here is the attribution of a "mercenary" when clicked on the correct button.
public Player player;
public void AddMercenary()
{
player.playerClass = TacticsActions.Classes.Mercenary;
player.name = player.playerClass.ToString();
gen = GetComponent<General>();
gen. allPlayers.Add(player);
}
(gen simply link to another script where the list public List<Player> allPlayers = new List<Player>();
is)
The code work fine except if I pick a mercenary then a priest, for example, the list will show 2 priests. I understand the problem is because player is a global variable but I can't find a way to make it local ( simply putting Player player=new Player();
inside the AddMercenary function sends back an error message)
If someone could help me I would appreciate it a lot.
Answer by cdr9042 · Jan 09, 2019 at 02:17 AM
when you Add(player) you didn't add a new player, you added a reference to the player. So after you added player twice, the list simply contain two references to the same player.
You have to create a copy of the player then add that copy to the list. One way to do it:
var newPlayer = new Player(player);
gen.allPlayers.Add(newPlayer);
You're getting an error because Player's constructor require a Player parameter, if you want to use new Player(), add a constructor for Player with no parameter
Yes, it works. Thanks a lot for the quick answer. I think I understand how serializable variables work now, thanks to your explication, so time to experiment.
Your answer
Follow this Question
Related Questions
adding items to my list 1 Answer
A node in a childnode? 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers