I’m trying to make a player editable keybinding menu.
The player clicks a button and they will be able to change the key binding.
I want to make sure the player hasn’t used the same key twice.
The debugs are there to see what the heck is going on with my code.
//Using OnGUI because it handles events
void OnGUI() {
//currentKey it the object that is clicked to indicate the player wants to change that key
if (currentKey != null) {
Event e = Event.current;
if (e.isKey) { //make sure it's a key press
//create a dictionary that will be used later
Dictionary<string, KeyCode> keysToReplace = new Dictionary<string, KeyCode>();
Debug.Log(e.keyCode);
myKeys[currentKey.name] = e.keyCode; // change the key to the new keyCode
// check to see if any keys already have the same keyCode
foreach (var item in myKeys) {
Debug.Log(item.Key + " " + item.Value);
KeyCode itemValue = item.Value;
if (itemValue == e.keyCode) {//if the itemValue is the same it's a duplicate
keysToReplace.Add(item.Key, KeyCode.Question); // add this pair as a duplicate
Debug.Log("Changed " + item.Key + " to question " + KeyCode.Question);
} else { //the itemValue is not a duplicate
keysToReplace.Add(item.Key, item.Value); // add the pair as normal
Debug.Log("Didn't Changed " + item.Key + " to question " + item.Value);
}
}
// replace the dictionary with this new one that has been check for duplicate
myKeys = keysToReplace;
foreach (var item in myKeys) {
Debug.Log("my keys: " + item.Key + " " + item.Value);
}
foreach (var item in keysToReplace) {
Debug.Log("Keys to replace: " + item.Key + " " + item.Value);
}
ChangeButtonText(); //Change the button texts to show the player the change worked
currentKey = null; //stop the player from making another change
}
}
}