NullReferenceException error (C#)

Hey everyone,

I’m making tactical space game, where I use arrays to find and place my units. However, each time I want to play, my script doesn’t work properly, and it give this error: NullReferenceException: Object reference not set to an instance of an object.

it happens primarily when I do this:
if (GUI.Button(rectSelectionButton, spaceShip[j].Name)) (this line is placed inside a for-loop.)

If I replace the variable spaceship[j].Name with a simple string like “spaceShip”, the scripts works fine. I already initiated my array doing this:

SpaceShipClass[] spaceShip = new SpaceShipClass[3];
void Start()
{
        spaceShip[0].Name = "Space Shuttle";
}

SpaceShipClass looks like this:

    private string name; // The ship's name

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

I really don’t understand my error, please help me! ):
EDIT: note that the error appears in both the initialization of the variable and the use of it.
EDIT 2: the above scripts are shortened versions of the entire scripts. Please say if you want to see the entire scripts. :slight_smile:

~ Mikkelet

maybe try to make a constructor for the ShaceShip class

edited: n/m

I’ve already defined the other 2:

    void Start()
    {
        spaceShip[0].Name = "Space Shuttle";

        spaceShip[1].Name = "Space Craft";

        spaceShip[2].Name = "Mothership";
    }

and my for-loop looks like this:

for (int i = 0; i < spaceShip.Length; i++)

EDIT: saw your “n/m”.

@Nikolay: what do you mean?

I’m assuming your SpaceShipClass is a class, not a struct. In which case, you need to assign an instance of a SpaceShipClass to each entry before you can try to alter the .Name property:

private void Start()
{
	spaceShip[0] = new SpaceShipClass();
	spaceShip[0].Name = "Space Shuttle";
	
	spaceShip[1] = new SpaceShipClass();
	spaceShip[1].Name = "Space Craft";
	
	spaceShip[2] = new SpaceShipClass();
	spaceShip[2].Name = "Mothership";
}

It worked! TY! :smile:

~Mikkelet