How to set up UI Buttons to do the same as Keys on a Keyboard

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?

Here is an image of what I have:

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.

Look more at the UI examples to see details.

Here is the code I have so far:

using UnityEngine;
using System.Collections;

public class PlayerMover : MonoBehaviour {

public int speed;
public int fSpeed;
public int rSpeed;

public GameObject leftButton;
public GameObject rightButton;

void Update()
{

}

void FixedUpdate()
{
float rotatePlayer = Input.GetAxis (“Horizontal”);
transform.Rotate(new Vector3(0, 0, rotatePlayer) * rSpeed);

Vector3 movement = new Vector3 (0.0f, 0.0f, fSpeed);

rigidbody.velocity = movement * speed;
}

}

Is there anyway to add something in to make it so leftBut

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.

I should also say that I’m new to coding Unity