user462879
user462879

Reputation: 187

Creating an array of objects using initializers seems to fail

I have a GameObject we'll call the GM. Attached to it is a script that's meant to be the primary logical controller for a game.

In that script, somewhere, I have:

private dbEquipment equipment_database = new dbEquipment();

The relevant snippet from dbEquipment.cs:

public class dbEquipment {
    private int total_items = 13;
    private clEquipment[] _master_equipment_list;

    public dbEquipment() {
        _master_equipment_list = new clEquipment[total_items];
        _master_equipment_list[0] = new clEquipment {
            ... //large amount of object initializing here
        };
        ... //etc, for all 13 items
    }
}

When I run Unity, I get:

NullReferenceException: Object reference not set to an instance of an object

Pointed at the line:

_master_equipment_list[0] = new clEquipment { ...

I tried running through the array and initializing every clEquipment object to an empty clEquipment() first:

for(int x = 0; x < total_items; x++) { _master_equipment_list[x] = new clEquipment(); }

just to be totally sure that the array was actually filled, but I got the same result.

I've also tried changing it to be a List<clEquipment>, and changing everything appropriately -- no dice.

Any ideas?

Upvotes: 1

Views: 172

Answers (2)

7200rpm
7200rpm

Reputation: 568

You might want to post the code for the clEquipment class. You say you tried initializing every object...did you do that before the break line? If it didn't break, thats a good sign.

Also, hard to tell from your code, but do you need a "()" in the initialization where it breaks? Just a thought

_master_equipment_list[0] = new clEquipment () {

Upvotes: 0

Jace
Jace

Reputation: 3072

My guess is that you may been including a null reference in the section that says //large amount of object initializing here when you create a new clEquipment.

_master_equipment_list[0] = new clEquipment {
    ... //check for nulls here
};

Upvotes: 4

Related Questions