0

I'm new with unity and c#. I have a class with subclass as below. Now I want to add new data inside the list of friends.

[Serializable]
public class PlayerData
{
    public string playerName;
    public string playerId;
    public Friend[] friends;
}

[Serializable]
public class Friend
{
    public string playerName;
    public string playerId;
}

I want to add new friend in the friend class list. Code I have tried till now.

public string AddFriends(string friendId)
    {
        PlayerData pd = playerDataDict[playerId];
        Friend friend = new Friend();
        friend.playerId = friendId;
        pd.friends.Append(friend);
        return "sdwsd";
    }

Thank you

user7356972
  • 58
  • 12

1 Answers1

3

You should use a List<T>:

public List<Friend> friends = new List<Friend>();

And then it works as you expect (almost):

pd.friends.Add(friend);
ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • I already some friends in my `pd.friends` list. I just want to add one new member inside it. I'm learner to c# and unity. Hope you understand and help me with it. – user7356972 May 13 '20 at 09:11
  • I understand you entirely. Use a list. If you want a finitely-sized object, then use an array. If you want an expandable object (i.e. you can add more items): use a list. If you're setting "friends" elsewhere, then perhaps you can remove the `= new List()` - I'm not really sure how Unity works with this kind of thing. – ProgrammingLlama May 13 '20 at 09:20