Shuffle 4 UI Buttons

I have a script where i have 4 buttons that have answers, 1 is correct 3 are wrong. I’m trying to make a void that shuffles the positions of these 4 buttons to be random and I’m unsure how to get around it, as i’ve tried vectors, but they don’t rescale to fullscreen or other canvas sizes. here’s my current code:

public void Shuffle()
	{
		int num;
		num = UnityEngine.Random.Range(0,2);
		Transform B1T = this.Button1;
		Transform B2T = this.Button2;
		Transform B3T = this.Button3;
		Transform B4T = this.Button4;
		for(int i=0; i<8; i++)
        {
		    if (num == 0)
		    {
			    this.Button1.position = B2T.position;
			    this.Button2.position = B1T.position;
		    }
		    if (num == 1)
		    {
			    this.Button1.position = B3T.position;
			    this.Button3.position = B1T.position;
		    }
		    if (num == 2)
		    {
			    this.Button1.position = B4T.position;
			    this.Button4.position = B1T.position;
		    }
		}
	}

thanks!

try getting a list of all positions that you want them to have.

Then use this

// Knuth shuffle algorithm :: courtesy of Wikipedia :)
for (int t = 0; t < positions.Length; t++)
{
    Vector3 tmp = positions[t];
    int r = Random.Range(t, positions.Length);
    positions[t] = positions[r];
    positions[r] = tmp;
}

to shuffle it,

then do this:

i = 0
foreach (Transform button in buttons)
{
    button.position = positions[i]

    i++;
}

hope this helps

Definitely invest some programming skillpoints in learning arrays and lists, generally known as “collections.”

Anytime you have a construct like this that has N different things:

Use collections and it becomes something like:

public Transform[] AllButtonTransforms;

or

public Button[] AllButtons;

and you drag all buttons in there, then iterate the collection as @matskb shows above.

All that said, one rarely shuffles the UI: instead you shuffle the data going INTO the UI.

Otherwise start with any three or four of the thousands of quiz game tutorials already up on Youtube. They will (generally) contain all parts of what you need, from data authoring to shuffling and choosing to presentation and grading the user’s responses. All of those things must be correctly engineered to work together. Collections let you engineer it ONCE, not four separate times with four separate sources of typing mistakes.

If you want an example of using data to drive a dynamic number of buttons, see the attached simple dynamic UI package.

9557998–1351300–DynamicUIDemo.unitypackage (94.0 KB)

1 Like