There are many ways that you could accomplish what you are trying to do.
You could just use an array:
bool myBools[] = { false, false, false, false };
void SetAll(bool b) {
for(int i=0; i<myBools.Length; i++) {
myBools *= b;*
}
}
Or you could use a bitmask
(note: I have never done this in C# or with Unity before). [Check this out, though.][1]
Edited to explain maps (in C# they are called Dictionary
but in computer science in general, they are maps):
So in the above example we created an array of bools myBools
but now we want to be able to give each one a specific name and reference it by that name.
For example, let’s say we’re creating a basic inventory system of fruit (see comments below). In this super-simple example, we’ll just want to determine whether we even have any of a specific fruit.
We begin by creating a Dictionary
which will map from a string
to a bool
because we want to be able to determine if we have a fruit knowing only its name.
Below is some example code showing how you could create a basic inventory system:
using System;
using System.Collections;
using System.Collections.Generic;
public class ExampleClass {
//Declare our basic inventory
Dictionary<string, bool> fruitInventory = new Dictionary<string, bool>();
//A more advanced “how many do we have” inventory would be defined like this
Dictionary<string, int> fruitQuantity;
//We could also make a class for more advanced data
public class FruitInventoryData {
int numRotten;
int numFresh;
bool canMakeWine;
}
//And use a dictionary like this
Dictionary<string, FruitInventoryData> fruitAdvancedData;
public void ExecuteExample() {
//Add some fruit to our basic inventory
fruitInventory.Add(“apples”, true);
fruitInventory.Add(“bananas”, false);
//Can also access it like an array, but ONLY to change it.
//This causes an error, because we have no data on mangoes yet
//fruitInventory[“mangoes”] = false;
//But this does not, because we DO have data about bananas
fruitInventory[“bananas”] = true;
//We can be safe like this - it doesn’t get executed because we check if we have the key, first
if(fruitInventory.ContainsKey(“mangoes”)) {
fruitInventory[“mangoes”] = false;
} else {
fruitInventory.Add(“mangoes”, false);
}
//And we can also easily iterate over dictionaries
foreach(KeyValuePair<string, bool> fruitData in fruitInventory) {
string fruit = fruitData.Key;
bool haveThisFruit = fruitInventory[fruit];
if(haveThisFruit) {
Console.Write("We have " + fruit + "
");
} else {
Console.Write("We DO NOT have " + fruit + "
");
}
}
}
If you ran ExecuteExample
you would get this output:
We have apples
We have bananas
We DO NOT have mangoes
[And here is a link to this executing.][2]
[1]: Using a bitmask in C# - Stack Overflow
[2]: C, C++, Java, Python, PHP Online Compliers, Terminals and Editors