System.Array.IndexOf iterating when it should not
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, wheni = 0
; returns 2, wheni=1
, and so on until it returns -1, wheni = 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 whatSystem.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 [i] = true; } else if (i != System.Array.IndexOf(allKeys, key1)) { allKeys [i] = false; } } }
Any help would be appreciated,
Thank you
Answer by NoseKills · Oct 05, 2016 at 06:48 AM
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] = 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] = i == keyIndex;
}
}
Your answer
Follow this Question
Related Questions
Button locking/unlocking for loop using an object array & playerprefs 1 Answer
C# Having troubles with creating/referencing a random list. 1 Answer
How do you play an array of audio clips in sequence with dialogue system on mouse click? 0 Answers