Help with object script

I have this simple object I’m trying to create an array with and reference throughout the application:

public class ExerciseSteps
{
    public string instructionText;
    public GameObject gameObjectTarget;
    public string requiredTool;
}

But when I reference a position in the array, I get an error saying “NullReferenceException: Object reference not set to an instance of an object” What am I missing?

private ExerciseSteps[] exerciseSteps = new ExerciseSteps[stepsCount];

for(int i = 0; i<stepsCount; i++)
{
exerciseSteps[i].instructionText = "Some value here"; // getting the error on this line
}

You initialized the array by calling new and gave it a size. That reserves memory for a certain amount of objects, but does not fill it with objects. You then iterate it and access the first object, which was never created, thus get a NullReferenceException.

Initially fill the array with a for loop (or do it in the existing one) by assigning each array index a new ExerciseStep…s. Which by the way should probably be named in singular.

Could I do it by simply doing:

public class ExerciseSteps
{
    public string instructionText = "";
    public GameObject gameObjectTarget = null;
    public string requiredTool = "";
}

I’m not really sure how to fill it after initializing the size. I thought that’s what I was doing with it.

Thats the class definition. You are accessing elements in your array that do not exist. Just like you created the array, you need to create each entry. Something along those lines:

for(int i = 0; i<stepsCount; i++)
{
    // Currently exerciseSteps[i] contains nothing, if we accessed it -> NullReferenceException
    exerciseSteps[i] = new ExerciseSteps(); // Create an actual element for this index
    exerciseSteps[i].instructionText = "Some value here"; // Now we can work with that element
}

Thanks, been a long time since I’ve done this, can’t grab a hold of it again.

1 Like

It’s also subtle: if for instance your class had instead been a struct then what you did would have worked… a struct is a value type and hence cannot be null.

BUT! Making your class a struct makes ALL your code harder because you must copy out each element, manipulate it and put it back.

Doing it as a class and initializing it like Yoreki did is the best way.

And arrays cannot change size… if you need to add/remove entries, make it a List() instead of an array. :slight_smile:

Originally I had a struct, but that didn’t work either. It’s been so long since I’ve done this that I’ve forgotten most of it. What he suggested worked, so I can keep it like that now. LOL I’m getting old and can’t grasp this stuff like I used to be able to.

Push back against it my friend, it can be done and the feeling when you get it is amazing.

Be humble and don’t beat yourself up for forgetting or struggling with stuff.

Just get better by doing it again and again!

1 Like