Picking a Random Order for Levers

I am trying to create a system in which the script will contain an array of levers, each having a DIFFERENT ‘ID’ number, which will represent the order it must be pulled in. Unfortunately, it does not work and I need help determining why. The ‘ID’ numbers are often the same, while I am aiming for them all to be different. (There is 3 levers, by the way, although the script is designed to work with any number.)

The script currently iterates through the array of levers, and for each lever, randomly picks an integer, assigns it to a separate array of ints, and then iterates through that array, with a while statement that makes sure the new number is not the same as any of the previous ones. After all of this, the final integer is assigned to the “orderID” variable of the lever.

Basically put, it doesn’t work.

Heres my code: (I might also mention it is written in C#)

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class LeverPuzzle : MonoBehaviour {
	public List <GameObject> levers;
	public List <GameObject> leversInOrder;
	public List <int> orders;
	private int leverCount;

	void Start () {
		leverCount = levers.Count;
		foreach (GameObject lever in levers) {
			int randomInt = Random.Range (1, leverCount + 1);
			var leverScript = lever.GetComponent <LeverScript>();
			orders.Add (randomInt);
			foreach (int order in orders) {
				while (randomInt == order) {
					randomInt = Random.Range (1, leverCount + 1);
			leverScript.orderID = randomInt;

Any help is greatly appreciated. Thank you in advance!


It might be easier to create a random number dispenser class that will only dispense each number once, but in a random order:

Warning: Not tested but should work

using System;
using System.Collections.Generic;

public class RandomNumberDispenser {

	public readonly int from;
	public readonly int to;
	private List<int> _numbers;

	// Initialise with range from 1 to x
	public RandomNumberDispenser(int to) : this(1, to) {}
	// Initialise with inclusive range, i.e. 1 to 10
	public RandomNumberDispenser(int from, int to) {
		this.from = from;
		this.to = to;
		_numbers = new List<int>();
		for (int n = from; n <= to; ++n)
	// Return next random number
	public int Next() {
		// Select list index at random
		int i = Random.Range(0, _numbers.Count);
		int n = _numbers*;*
  •  // Remove number from list*
  •  _numbers.RemoveAt(i);*
  •  return n;*
  • }*

  • // Indicates if there are any more random numbers to dispense*

  • public bool hasFinished {*

  •  get { return _numbers.Count == 0; }*
  • }*



RandomNumberDispenser dispenser = new RandomNumberDispenser(levers.Count);
foreach (GameObject lever in levers) {

  • LeverScript leverScript = lever.GetComponent();*

  • leverScript.orderID = dispenser.Next();*

  • // If you still want to create an array of orders*

  • orders.Add(leverScript.orderID)*