I have a Unity mobile project where I am trying to use right/left movement using two UI buttons situated accordingly. The issue is that it only moves the player to the right/to the left one time, not continually when the player is holding the button down.
I'd like the player to be able to hold down a certain button and have the character move constantly in that direction until the button is released. I've tried making the void into a Coroutine, but nothing working works.
Here is my code. (rightCallable
and leftCallable
are attached to the buttons).
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerController : MonoBehaviour
{
public GameObject player;
public float speed = 1000f;
public GameObject left;
//this is so the player may also use the A and D keys if they want, and it works fine.
public void Update()
{
var movement = Input.GetAxis("Horizontal");
transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * speed;
}
//Below is what isn't working
public void rightCallable ()
{
StartCoroutine("moveRight");
}
public void leftCallable ()
{
StartCoroutine("moveLeft");
}
IEnumerator moveRight()
{
var movement = 1f;
transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * speed;
yield return null;
}
IEnumerator moveLeft ()
{
var movement = -1f;
transform.position += new Vector3(movement, 0, 0) * Time.deltaTime * speed;
yield return null;
}
}