List of Class, add item and set class vars

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class CharacterDB : MonoBehaviour
{
    [System.Serializable]
    public class Char
    {
        public string firstName;
        public string lastName;

    }

    public List<Char> Chars = new List<Char>();

    public void Start()
    {
        AddItem();
    }
    public void AddItem()
    {
        Chars.Add(new Char());
      
    }
}

Is there a way I can add items to my list of class and set the vars,

I want to set the strings firstName and lastName in my AddItem() void, how can I do that?

I tried :

Chars.Add(new Char("John","Cena"));

But It says that Char don’t contain a constructor that takes 2 arguments

Have you considered giving Char a constructor that takes 2 arguments?

1 Like

There are 2 ways, but first I would like to suggest naming a class Char could be very confusing since c# has a built in variable type named char. I would suggest expanding it out to Character, or PlayerChar ,etc

First Way:

Char tmp = new Char();
tmp.firstName = "John";
tmp.lastName = "Cena";
Chars.Add(tmp);

Second Way add a constructor:

public class Char {
         public string firstName;
         public string lastName;

         // empty constructor in case we want to make a blank char
         public Char()
         { }

         // Constructor that takes 2 arguments to fill in names
         pubilc Char( string first, string last)
         {
                     firstName  = first;
                     lastName = last;
          }
}

This will make this work:

Chars.Add(new Char("John","Cena"));
2 Likes

Char is a built in class used for storing individual characters. Like ‘A’, ‘B’, ‘#’ ect. I would strongly suggest changing the name.

Sniped.

2 Likes

Why not kill some lines? The tmp variable doesn’t do anything (and look at it’s name), and C# supports object initializers. Constructors that just set public variables are silly:

Chars.Add(new Char {
    firstName = "John",
    lastName = "Cena"
});
1 Like

What if you needed to do this:

Char tmp = new Char();
if (x < 0)
   tmp.firstName = "John";
else
    tmp.firstName = "Joe";
tmp.lastName = "Cena";
Chars.Add(tmp);

I agree most situations it silly to create a temporary variable when a initializer is availabe. Sometimes it is useful, and I was just showing him the possiblity exists

1 Like