I know this has been asked many, many times. However, in all the posts I’ve looked at (6 so far) the problem was that they destroyed the object before using it, or there was a typo, or they were using List<>s. I have a medium-sized class (large enough to not post the whole thing here at least) with a table that stores values for upgrades. This is set up as an array of 2D arrays.
It is declared like so:
float[][,] upgrades;
and later it is initialized like this:
void Start() {
upgrades = new float[5][,];
upgrades[0][0,0] = 15; //example value
I was setting this up as sort of backend, and as a result I didn’t actually get around to testing this until I was almost ready to begin putting it into the game. When I started finally testing, I recieved the error in the title. The exact code I used to trigger this is
If your Start() function looks just like you’ve written it, then I bet that it already throws an exception. And then if Unity decides to keep on executing other code, your testUpgradeTable() function should throw the same error for the same reason, whenever it gets called.
When you create a new array of float[5][,], what you’re doing is create an array of 5 references to 2-dimensional arrays. Except that these references are initialized to null. You don’t actually have 5 literal 2D arrays; you just have 5 slots which are capable of referencing 2D arrays. You’ll need 5 more new statements to create the actual 2D arrays themselves (or a single new statement in a loop which executes 5 times, depending on your needs). Only then will you be able to access the first array using the first accessor [0], and then access the first element of the first row of that array using the second accessor [0,0].
@AndyGainey has the right of it. Jagged arrays need to be initialised twice. Once for the outer array. And once for each inner array.
However such complicated array structures normally hide something odd going on in the code. It’s typically more maintainable to wrap the inner collections. Which would have made the error obvious.
Thanks a bunch, I must’ve glazed over that part of the c# docs.
I ended up replacing this construct with a 3D array, as there was no real need to use a jagged array in this case.