How to use class with array

Hi ! Currently trying to use an array with a public class, like so:

    Adventurers[] AdventurersArray = new Adventurers[128];
    public Text txt_Name, txt_HP, txt_Ability;

    public class Adventurers
    {
        public int advID;
        public string name;
        public int hp;
        public string ability;
    }

    public void Update()
    {
       
    }
    public void btt_GenerateAdventurer() //test button that generate an adventurer
    {
        AdventurersArray[0].name = "kevin";
        AdventurersArray[0].hp = Random.Range(0, 10);
        AdventurersArray[0].ability = "fireball";
        txt_Name.text = "Name: " + AdventurersArray[0].name;
        txt_HP.text = "HP: " + AdventurersArray[0].hp;
        txt_Ability.text = "Ability: " + AdventurersArray[0].ability;
    }

That’s what I came with after some looking up here and there. But, it of course don’t work and the console says “NullReferenceException: Object reference not set to an instance of an object” on line 32. What should I do to make it work ? Thanks in advance.

In line 1 above you make the array. At that moment it is an array of 128 nulls.

Now before line 18 you need to allocate an Adventurers!

AdventurersArray[0] = new Adventurers();

I also recommend naming your class Adventurer, not the plural, since it is only one in your array. Then you can just call the array “Adventurers” and leave off the “Array.” That way if it becomes some other kind of collection (such as a List()) in the future, it’s not misleading.

The first thing you need to do with a slot in an array is initialize it. When you say AdventurersArray = new Adventurers[128];, you have an array containing 128 copies of “null”. Each one you use, you need to initialize:

adventurersArray[0] = new Adventurers();

(And while it’s okay for figuring out how arrays work, if you find yourself setting individual elements’ information in code (as on lines 18-20), you’re probably not using arrays very effectively. Normally, you’d load them from files, have the class be serializable so that you can edit them in the inspector, or something along those lines.)

1 Like