I have an Array of bools and when the function Key1Pushed()
is called I want to iterate through the array setting them all to false, except for the bool key1
which I want to set to true
.
I believe this code should work however whenever I call Key1Pushed()
I encounter 2 issues:
-
System.Array.IndexOf(allKeys, key1)
returns 1, when i = 0
; returns 2, when i=1
, and so on until it returns -1, when i = 7
.
I don’t know why it’s iterating, and I dont know why it starts with returning 1.
-
Even though in every case i
does not equal what System.Array.IndexOf(allKeys, key1)
returns, it passes the first if condition and sets all of the values in my array to true.
public class InputKey : MonoBehaviour {
public bool[] allKeys;
private bool key1;
private bool key2;
private bool key3;
void Start () {
allKeys = new bool[] { key1, key2, key3 };
}
public void Key1Pushed () {
for(int i = 0; i < allKeys.Length; i++) {
if (i == System.Array.IndexOf(allKeys, key1)) {
allKeys *= true;*
_ allKeys = false;_
* }*
* }*
}
Any help would be appreciated,
Thank you
A bool is a value type, so when you assign a boolean to another boolean variable, you don’t create a reference to the original boolean, instead the value of the first gets copied to the second. In other words, you don’t get 2 variables referencing the same piece of data, you get 2 separate variables with the same value.
You can easily test this
key1 = false;
allKeys = new bool[] { key1 };
key1 = true;
Debug.Log(key1); // true
Debug.Log(allKeys[0]); // false
// Changing key1 doesn't change the copy in the array & vice versa
For the same reason IndexOf() doesn’t work as you probably think it does in this case. Because bool is a value type, IndexOf will just find the first index that holds the same value as the second parameter. You can test this too
key1 = false;
key2 = false;
allKeys = new bool[] { key1, key2 };
Debug.Log(System.Array.IndexOf(allKeys, key1))); // 0
Debug.Log(System.Array.IndexOf(allKeys, key2))); // 0
// Both return 0 because index 0 contains false and both
// lines check to find the index of "false" in the array
Since your Key1Pushed()
handles only 1 index/key, you don’t have to use IndexOf(). I believe you could just do
for(int i = 0; i < allKeys.Length; i++) {
allKeys *= i == 0; // set index 0 to true, others to false*
}
You could even make the index to be a function parameter
public void KeyPushed (int keyIndex) {
for(int i = 0; i < allKeys.Length; i++) {
allKeys = i == keyIndex;
}
}