Hello, I’m trying to set up a game to work on mobile but I can’t get the UI buttons to work as if the keyboard keys were being pressed. I have two buttons, Left and Right, I need them to do the same thing as if I pressed ‘A’, for left, and ‘D’, for right. Can anyone help me figure this out?
Basically you want to make a function for each of the actions you can do:
public void DoActionLeft() {...}
public void DoActionRight() {...}
Then in your Update() function, you would check Input.GetKeyDown( KeyCode.A) and KeyCode.D and call the appropriate function.
If you are already reading the keys properly, I assume you’re doing something like the above.
Now, create the UI buttons and go into their event handlers (for each button) and make a reference to the script where the above functions reside, and tell the button event handler to call those functions when either button is pressed.
You are better off adding a layer of abstraction between Unity’s input and your code. (This is incidentally also the easiest way to make runtime configurable input).
So your player code calls MyInput.GetAxis. Inside MyInput you store the various and compute the various axes based on Input.GetKey. You would also have your various UI buttons feed into MyInput.