How do I make my character move left,right and jump when click ui buttons using this code?

using UnityEngine;
using System.Collections;

public class Player: MonoBehaviour {

public float maxspeed = 10f;
bool facingRight = true;

Animator anim;

bool grounded = false;
public Transform groundCheck;
float groundRadius = 0.2f;
public LayerMask whatIsGround;
public Vector2 jumpDirection = new Vector2(1f, 1f);
public Vector3 groundCheckOffset = new Vector3(0f, -1f, 0f);
public float jumpFocre = 500f;
bool doubleJump = false;

void Start ()
    anim = GetComponent<Animator> ();

void FixedUpdate () {
    grounded = Physics2D.OverlapCircle(groundCheck.position, groundRadius, whatIsGround);
    grounded = Physics2D.OverlapCircle(transform.position + groundCheckOffset, groundRadius, whatIsGround);
    anim.SetBool ("Ground", grounded);

    if (grounded)
        doubleJump = false;

    float move = Input.GetAxis ("Horizontal");

    anim.SetFloat ("Speed", Mathf.Abs (move));

    GetComponent<Rigidbody2D>().velocity = new Vector2(move * maxspeed, GetComponent<Rigidbody2D>().velocity.y);
void Update()

    if((!doubleJump) && Input.GetKeyDown ("up"))
        anim.SetBool("Ground", false);

        float move = Input.GetAxis ("Horizontal");

        jumpDirection.x = move;
        GetComponent<Rigidbody2D>().AddForce(jumpDirection.normalized * jumpFocre);

        if(!doubleJump && !grounded)
            doubleJump = true;


    void Flip()
    facingRight = !facingRight;
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;    

Make the float move variable a class variable. Then create 2 methods which the left and right UI buttons will call on Pointer Down, e.g. MoveLeft() and MoveRight(). Inside them, set move = -1 for left and move = 1 for right.

If you want the character to stop if the buttons aren't pressed, you can also make a StopMoving() method on Pointer Up for both buttons that sets move = 0.

  • \$\begingroup\$ It keep saying Assets/code/Player.cs(74,17): error CS0131: The left-hand side of an assignment must be a variable, a property or an indexer \$\endgroup\$ – Bob May 4 '15 at 13:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.