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
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
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;
}
}
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:
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