populate 2d array with existing grid of gameobjects

Hi all, sorry for my ignorance but I would like to populate a 2d array on a spawner script with a grid of cubes already present in my scene. The cubes have an instance of a custom class “grid coordinates” on them which defines coordinates stored as x/y floats and which row/column they belong to (for later use).

I’m not sure what to do to get them into my array, I can create the array with the right number of indexes, but then when I get to the end of the two for loops I don’t know how to reference my cubes and match them with the array coordinates.

From my understanding I’m assuming you want to make a 2D array containing your cubes. One simple way is making a serialized field that will have it’s references specified in the editor. But since the editor can’t serialize a 2D array, an alternative option is to make a custom class, put an array there and then make an array of those class instances.

Here’s a quick example:

using UnityEngine;

public class TestScript : MonoBehaviour
{
    public CollectionOfCubes[] cubes = new CollectionOfCubes[0];

    private void Start()
    {
        for (int i = 0; i < cubes.Length; i++)
        {
            for (int j = 0; j < cubes*.instances.Length; j++)*

{
GameObject currentCube = cubes*.instances[j];*
Debug.Log($“Cube name: {currentCube.name}”);
}
}
}
}

[System.Serializable]
public class CollectionOfCubes
{
public GameObject[] instances = new GameObject[0];
}
If you want to write a better solution, maybe something that doesn’t require dragging the cube references by hand, you can check out some of the following references:
_*https://docs.unity3d.com/ScriptReference/Transform.GetChild.html*_
_*https://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html*_
_*https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html*_

@Quickz Thank you so much, that’s really helpful. I was thinking of assigning them explicitly to the 2D array as there are not too many of them, but I like your idea much better!