0

I am making a board game. There is a grid. Grid has many tiles. Board image. Tiles are child game objects of grid. I want to reorder tiles randomly at the end of each level.

    foreach (GameObject tile in tileList)
    {
        tile.transform.SetSiblingIndex(UnityEngine.Random.Range(0, tileCount));
    }

I tried like this. Is this snippet of code correct?

All items are UI element. They aren't sprite. Grid has grid layout group component. Positions of tiles are automatically assigned by grid.

Fx Games
  • 1
  • 4
  • no, you might end up with multiple objects with the same sibling index – Jimmar Jul 04 '21 at 13:20
  • @Jimmar no that's not true .. If you assign two objects the same index it will just move the following children one index higher .. kind of similar to what `InsertAt` in a list would do – derHugo Jul 04 '21 at 14:11
  • `Is this snippet of code correct?` .. well does it do what you want to achieve? – derHugo Jul 04 '21 at 14:14
  • @derHugo Sometimes the correct answer tiles are very close to each other. – Fx Games Jul 04 '21 at 14:20
  • @FxGames well .. random is random so yes this might happen from time to time ;) .. there is a huge difference between randomness and equaly spreading ... there might occur clusters in random patterns – derHugo Jul 04 '21 at 14:21

2 Answers2

1
public void Demo()
    {
        Fun1 ();
        //Fun2 ();
    }

    public void Fun1 ()
    {
        // remove group children
        removeChildren ();
        //sort List
        tileList.Sort (sortList);
        GameObject parent = new GameObject();
        foreach ( GameObject tile in tileList )
        {
            tile.transform.SetParent (parent);
        }
    }

    private int sortList (int a , int b)
    {
        return a - b;
    }

    public void Fun2()
    {
        foreach ( GameObject tile in tileList )
        {
            tile.transform.SetSiblingIndex (UnityEngine.Random.Range (0 , tileCount));
        }
        LayoutRebuilder.ForceRebuildLayoutImmediate (GameObject.GetComponent<RectTransform>());
    }

you can test LayoutRebuilder.ForceRebuildLayoutImmediate see see.

chuanSu
  • 21
  • 2
-1

Setting the sibbling index wont move the tiles. What you can is a quick shuffle. like you would to randomize a list.

 public void ShuffleBoard()
{        
    int n = tileList.Count;
    while (n > 1)
    {
        n--;
        int k = UnityEngine.Random.Range(0, n + 1);
        Tile value = tileList[k];
        tileList[k] = tileList[n];
        tileList[n] = value;
    }
}
leo Quint
  • 777
  • 1
  • 5
  • 12