using buttons for touch controls

hello,

I have a player controller working perfectly using W, S and Space keys to move up, down and shoot but I want to convert these into mobile touch controls. I have added some buttons to my canvas but I don’t know how to convert to touch controls. I know I probably need a separate script and set the buttons up with on click functions on that script but I don’t know how to go about the script.

Here is my current player controller script:

using System.Collections.Generic;
using UnityEngine;

public class PlayerMovement : MonoBehaviour
{

    public float maxSpeed = 5f;

    public float shipBoundryradious = 0.5f;

    public GameManager theGameManager;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {


        Vector3 pos = transform.position;

        pos.y += Input.GetAxis("Vertical") * maxSpeed * Time.deltaTime;

        if (pos.y + shipBoundryradious > Camera.main.orthographicSize)
        {
            pos.y = Camera.main.orthographicSize - shipBoundryradious;
        }
        if (pos.y - shipBoundryradious < -Camera.main.orthographicSize)
        {
            pos.y = -Camera.main.orthographicSize + shipBoundryradious;
        }

        transform.position = pos;
    }

    void OnCollisionEnter2D(Collision2D other)
    {
        if (other.gameObject.tag == "killbox")
        {
            theGameManager.RestartGame();
        }
    }
}

thanks,

@Kiesco91

You know, if you don’t know this, you probably can google for this :)?

This is more like a LMGTFY question. Google “unity touch buttons” / “unity touch” and you’ll find several tutorials on this topic.

Unity UI system buttons work with touch too without any extra work IIRC.

But you could also use plain touches, without buttons if you also need multi-touch/gestures.

However - this is one setup what you can/could use:

Create a script, that has a method, then assign it to your button. When you click button, it gets called.

Then from this method, you can call your movement code / set some variables instead of setting them using Input.GetKey.

Button variable here is just an enum type field, that you can change in inspector (left, right, up, down) so that you don’t have to use some string or different methods for each of your buttons.

Appriciate your reply, i have tried googling 2 or 3 different ways but they just don’t seem to work how I hoped. I will have another look and go through what you have said though and see where this leads me.

Thanks