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

0

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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<Friend>() - I'm not really sure how Unity works with this kind of thing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.