- Home /
List.Add (new CustomClass()) results in empty entry
I'm trying to create multiple character records belonging to a class Custom_Character in a simulation class, and I had thought the following code would result in a list with ten instances of that class, but when I run it, all ten slots are empty:
public List<Custom_Character> characterList;
void GenerateCharacter(int number){
Custom_Character newCharacter;
for (int i = 0; i < number; i++) {
newCharacter = new Custom_Character();
characterList.Add (newCharacter);
}
}
Is there an obvious mistake in how I'm doing this?
I did something simmilar but on network adding a new class.. this is the script hope you can figure it: using UnityEngine; using System.Collections; using System.Collections.Generic;
public class PlayerDatabase : $$anonymous$$onoBehaviour {
public List<PlayerDataClass> PlayerList = new List<PlayerDataClass>();
void OnPlayerConnected(NetworkPlayer networkPlayer)
{
//Add the player to the list in PlayerDataBase.
networkView.RPC("AddPlayerToList", RPC$$anonymous$$ode.AllBuffered, networkPlayer);
}
[RPC]
void AddPlayerToList (NetworkPlayer nPlayer)
{
//Create a new entry in the PlayerList with network ID to capture.
PlayerDataClass capture = new PlayerDataClass();
capture.networkPlayer = int.Parse(nPlayer.ToString());
PlayerList.Add(capture);
}
}
public class PlayerDataClass
{
public int networkPlayer;
public string playerName;
public int playerChar;
public PlayerDataClass Constructor()
{
PlayerDataClass capture = new PlayerDataClass();
capture.networkPlayer = networkPlayer;
capture.playerName = playerName;
capture.playerChar = playerChar;
return capture;
}
}
Reading this through and comparing to my version helped me spot the error, thank you! Once I stopped extending $$anonymous$$onoBehaviour in my class, it was created and serialized properly :)
Answer by DeveshPandey · Nov 06, 2014 at 06:38 AM
Try this.
public List<Custom_Character> characterList = new List<Custom_Character>();
void GenerateCharacter(int number){
Custom_Character newCharacter;
for (int i = 0; i < number; i++) {
newCharacter = new Custom_Character();
characterList.Add (newCharacter);
}
}
This plus not extending my class works perfectly, thank you :)
Your answer
