Stop Player from moving when button pressed

Hi

so i’m using the ui buttons to move my player left and right on the x axis.

the thing i need help on is to stop the player from moving when the buttons are not pressed.

what i would prefer is that if the player is moving right and i press the left button the player will stop, same goes for if the player is moving left and i press the right button the player will stop.

if that cant be don’t then how do i stop the player from moving when button is not pressed.

code for Right Button

public float moveSpeed = 12500;
public GameObject character;

private Rigidbody characterBody;

// Use this for initialization
void Start () {

	characterBody = character.GetComponent<Rigidbody>();
}

// Update is called once per frame
public void Update () {
	int i = 0;
	//loop over every touch found
	while (i < Input.touchCount) {
		if (Input.GetTouch (i).position.x != null) {
			//move right
			RunCharacter (1.0f);
		}
		++i;
	}
}

private void RunCharacter(float horizontalInput){
	//move player
	characterBody.AddForce(new Vector3(horizontalInput * moveSpeed * Time.deltaTime, transform.position.y, transform.position.z));

}

code for Left Button

public float moveSpeed = 12500;
public GameObject character;

private Rigidbody characterBody;

// Use this for initialization
void Start () {

	characterBody = character.GetComponent<Rigidbody>();
}

// Update is called once per frame
public void Update () {
	int i = 0;
	//loop over every touch found
	while (i < Input.touchCount) {
		if (Input.GetTouch (i).position.x != null) {
			//move left
			RunCharacter (-1.0f);
		}
		++i;
	}
}

private void RunCharacter(float horizontalInput){
	//move player
	characterBody.AddForce(new Vector3(horizontalInput * moveSpeed * Time.deltaTime, transform.position.y, transform.position.z));

}

Hi @uzzy121 , I’ve changed your changed a little to stop if touch count is zero.

    public float moveSpeed = 12500;
    public GameObject character;
    private Rigidbody characterBody;
    // Use this for initialization
    void Start()
    {
        characterBody = character.GetComponent<Rigidbody>();
    }
    // Update is called once per frame
    public void Update()
    {

        //loop over every touch found
        if(Input.touchCount >= 1)//at least one touch found
        {
            for(int i =0; i < Input.touchCount;i++)
            {
                RunCharacter(1.0f);//move right
            }
        }
        else //no touch found
        {
            //player will stop , you can set velocity to zero for an instant stop
            characterBody.velocity = Vector3.zero;

        }
    }
    private void RunCharacter(float horizontalInput)
    {
        //move player
        characterBody.AddForce(new Vector3(horizontalInput * moveSpeed * Time.deltaTime, transform.position.y, transform.position.z));
    }