I want to create a 2D array of Transforms

How would I go about creating a 2D array of Transforms.

8639835--1161963--upload_2022-12-6_15-17-31.png

Simply doing this doesn’t allow me to drag and drop any gameObjects into the array as it is a 2D array.

So I do what I’ve coded below instead

There’s something I’m not getting and I don’t know what it is.

I just want to create a 8x8 grid as an array for a Chess game in which:

piece.transform = boardPos[2,4];

which will move the piece’s location to that of the gameObject in position 2,4

8639835--1161981--upload_2022-12-6_15-38-10.png

This is another solution that I thought would work which is by setting the value in boardPos to the index within the index of xPos which is an array of the “y positions”. But this doesn’t seem to work as it outputs the error “Cannot implicitly convert type ‘UnityEngine.Transform[ ]’ to 'UnityEngine.Transform”

How do I assign gameObjects to every index in the 2d array without referencing every single gameObject since I can’t drag and drop

8639835--1161963--upload_2022-12-6_15-17-31.png
8639835--1161975--upload_2022-12-6_15-33-35.png

It looks like in your start method, you have xPos incorrect.
What you probably want is a jaggedArray

You could also go with the example here at the bottom using the struct

You need a Transform[ ][ ] (an array of arrays or a jagged array like @Brathnann said) which items can be accessed by xPos*[j]*

1 Like

Just to make that a bit more clear in general. Arrays always have a certain element type. The element type is always to the left of the square brackets So Transform[ ]is an array that contains Transforms. On the other hand Transform[ ][ ] is an array which element type is an array of Transforms. So the type nesting goes from right to left for arrays. Accessing the different “layer” on the other hand works the other way round. So when you index a jagged / nested array like this Transform[ ][ ] xPos;, the first index gives you an element of the outer array. So you get a Transform[ ] back

Transform[] sub = xPos[5];
Transform t = sub[2];

This is the same thing just in one line:

Transform t = xPos[5][2];

Types can get really confusing, but once you understand how the array syntax work, it’s pretty easy. You can even create crazy types like

private List<int[]>[] myArray;

This is an array of a generic List that in turn contains arrays of integers. Just keep in mind that array are objects themselfs and need to be created at some point. Things that are serializable in the inspector can get initialized through the inspector itself. However Unity does only support one dimensional arrays and does not support jagged arrays. Though it does support arrays of serializable objects which also contain an array. So you get a nested array, but uglier :). At least it can directly be serialized and displayed in the inspector.

1 Like