Writing an object to an Array with index?

Hey guys, I’m having a bit of a brain fart at the moment despite being fairly experienced with C#.

Anyway, when I attempt to assign a value to an index in a list (of which the object at that index is currently null/not defined) an ArgumentOutOfRangeException occurs, what am I doing wrong here? Or am I looking for a different type of array/list?

Code:
public List checkpointPassedListBool = new List();

In a method, this is called (where ‘id’ is a parameter of the method)

checkpointPassedListBool[id] = true;

  • Keep in mind checkpointPassedListBool[id] is currently empty/null, and I just want to assign the value.

You would be better off creating a fixed size array with the length being the highest ID you have. Otherwise you are trying to change elements that aren’t yet there.

Can’t really do that, as the only limitation to IDs is the players skill.

Why not create a struct?

public struct Checkpoint {
        public Checkpoint(bool passed, int id){
            this.passed = passed;
            this.id = id;
        }

        bool passed;
        int id;
    }

and then add them to the list…

List<Checkpoint> checkPoints = new List<Checkpoint>();

checkPoints.Add(new Checkpoint(true, id));

…then you can find them again by searching through the list in whichever way you like.

You’re a legend, never thought of using structs. Cheers!

Just for the record , I think maybe the problem you were having initially was the size of the List.
A List will grow, as you add to it, but you cannot access an index which is beyond the length (size) of the list at the current time. So, for future knowledge/reference… if they were sequential, you could simply use List’s ‘Add’ method as the player progresses and it would “be at the right index”. :slight_smile:

I knew that, but the purpose of the array was not intended to be added sequentially.

Then you’d have to fill it with ‘empties’ to a certain size, overwrite when the right situation occur(ed), and expand as needed :wink:
Since you probably took the other way, it’s moot now, but just for talking it out’s sake. :slight_smile: