Here’s something I’ve been trying to figure out:
I have an array with 8 elements (currently only two set up). I have some code that picks a random element and prints it and after three seconds, resets and picks a new number.
I also have the number keys 1-8 for the controls.
I want to print a “you got it correct” message if I press the correct key when that number is chosen before it resets.
The part that I haven’t managed yet is setting the keys to react to the numbers chosen in the array.
I feel like it’s something simple that I’m missing.
I’m not clear what you mean by this. Keys don’t “react” to anything. You check for input, and if it there you do something, if not you do something else or nothing. It is pretty simple to just brute force write a method to check for those 8 keys though: (looks like garbage code, but it should work just fine)
//Returns a number 1-8 if pressed this frame
//Returns -1 if no acceptable key was pressed this frame
private int checkForInput()
{
int keyPressed = -1;
if (Input.GetKeyDown(KeyCode.Alpha1)
{
keyPressed = 1;
}
if (Input.GetKeyDown(KeyCode.Alpha2)
{
keyPressed = 2;
}
if (Input.GetKeyDown(KeyCode.Alpha3)
{
keyPressed = 3;
}
if (Input.GetKeyDown(KeyCode.Alpha4)
{
keyPressed = 4;
}
if (Input.GetKeyDown(KeyCode.Alpha5)
{
keyPressed = 5;
}
if (Input.GetKeyDown(KeyCode.Alpha6)
{
keyPressed = 6;
}
if (Input.GetKeyDown(KeyCode.Alpha7)
{
keyPressed = 7;
}
if (Input.GetKeyDown(KeyCode.Alpha8)
{
keyPressed = 8;
}
return keyPressed;
}
Once you have an integer representation of what key was pressed, it then becomes easy to compare against your array. Though I’m not clear if you need to compare against the value at a specific index or the index number itself, since I don’t know what you mean by “the numbers chosen in the array.” If it is the index, then just remember arrays are indexed starting at 0, not 1, so just subtract 1 from the value of whatever key was pressed and you get the index within the array they chose. Do your comparison and they win or lose.
I would do something like this:
using UnityEngine;
public class KeyCodeTest : MonoBehaviour
{
private readonly KeyCode[] _keyCodes =
{
KeyCode.Alpha1, KeyCode.Alpha2, KeyCode.Alpha3, KeyCode.Alpha4,
KeyCode.Alpha5, KeyCode.Alpha6, KeyCode.Alpha7, KeyCode.Alpha8
};
private int CheckKeyPress()
{
for (var i = 0; i < _keyCodes.Length - 1; i++)
{
if (Input.GetKeyDown(_keyCodes[i]))
{
return i + 1;
}
}
return 0;
}
private void Update()
{
if (CheckKeyPress() != 0)
{
// TODO Check if it is correct
}
}
}
I don’t think I explained this very well but through each of your replies I was able to get the code working the way that I needed it to.
Thank you both. 