An array of bools with random true and false elements


I have made a built in array of bools and I was wondering if anyone knew of a way to use random.range or any other method to switch the true statement into different elements slots in the array.

	testArray2 [0] = true;
	testArray2 [1] = false;
	testArray2 [2] = false;
	testArray2 [3] = false;

so at the moment [0] is true I was wondering if there is a way to randomly switch the single true statement to say [1] and keep all the others false. That way I can have several If statements that can say…

	if (testArray2[0])
		print ("working");
		gameObject.renderer.material = Red;
		gameObject.tag ="redEnemy";
	if (testArray2 [1])
		gameObject.renderer.material = Blue;
		gameObject.tag ="blueEnemy";
	if (testArray2 [2])
		gameObject.renderer.material = Green;
		gameObject.tag ="greenEnemy";
	if (testArray2 [3])
		gameObject.renderer.material = Yellow;
		gameObject.tag ="yellowEnemy";

and this is how I can make it random (if the array was an INT)

	System.Random random = new System.Random();
	randomTest = testArray2[random.Next(0, testArray2.Length)];

Any help is greatly appreciated as this is uni coursework. Thank you kindly.

Sure, don’t use an array at all. It makes no sense in this case. Just use a single integer variable to specify which statement you want to execute:

int selection = 0;
// [...]
if (selected == 0)
    // ...
else if (selected == 1)
    // ...
else if (selected == 2)
    // ...


In your case it seems you want to distinguish different enemy types. Usually you simply create a prefab for each enemy type and put the prefabs in an array from which you select a certain type to be instantiated.

However if you just want to set a Material and a tag you can use a custom class like this:

public class EnemyType
    public string tag;
    public Material material;

Inside you actual enemy MonoBehaviour you could declare an array like this:

public EnemyType[] enemyTypes;
public int enemyType = 0;

void Start()
     renderer.material = enemyTypes[enemyType].material;
     gameObject.tag = enemyTypes[enemyType].tag;

However seperate prefabs are usually much more easier to maintain and to work with. But without more information on the purpose of your code snippet we can’t say much more about this.

Since you write it’s for a real school course, you may as change the if into a lookup (too confusing for many programmer/artists, but in school you’ll learn it anyway):

public Color[] EnemyCols; // set in Inspector
public string[] EnemyTags = {"redE", "greenE", ... };

int selected = 0; // single-var trick from Bunny's reply

// replaces all of the ifs:
gameObject.renderer.material = EnemyCols [ selected ];
gameObject.tag = EnemyTags [ selected ];