unity – save generated gameobject to an array for shuffling

First you create an array with the number of entries you need:

GameObject() newGameObjects = new GameObject(array2D.GetLength(0));

Then you put each newly created game object into entries of that array after you created it:

newGameObjects(i) = n;

Then you shuffle it:

Shuffle(newGameObjects);

Full code:

public void Start()
{

    GameObject spritesRoot = GameObject.Find("SpritesRoot");
    Debug.Log("Array length: " + array2D.GetLength(0));
    GameObject() newGameObjects = new GameObject(array2D.GetLength(0));

    for (int i = 0; i < array2D.GetLength(0); i++)
    {
        Debug.Log("x: " + array2D(i, 0));
        Sprite newSprite = Sprite.Create(source, new Rect(array2D(i, 0), array2D(i, 1), array2D(i, 2), array2D(i, 3)), new Vector2(0.5f, 0.5f));
        GameObject n = new GameObject();
        SpriteRenderer sr = n.AddComponent<SpriteRenderer>();
        sr.sprite = newSprite;
        n.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(array2D(i, 0), array2D(i, 1),0),0);
        n.transform.parent = spritesRoot.transform;
        newGameObjects(i) = n;
    }

    Shuffle(newGameObjects);

}

As written here, all of this is actually pretty pointless, because newGameObjects is a local variable which will get discarded as soon as the Start method is over. So the shuffled order will never be used for anything. But I assume you have a good reason why you want an array with those objects in random order and know what to do with it.