wizard drifter
wizard drifter

Reputation: 11

Unity 2D How to set touch button?

I make a game for android and i need to have UI Joystick and UI Attack Button on the game screen. I already have the workable Joystick and Attack Button on Space key for keyboard. Can someone told me how should i switch code from keyboard Input to Touch Input? P.S. i'm sorry for my english.

        if (Time.time >= nextAttackTime)
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Attack();
            nextAttackTime = Time.time + 2.5f / attackRate;
        }
    }

Upvotes: 1

Views: 2594

Answers (2)

nkazz
nkazz

Reputation: 560

Another way would be to work with the unity Button script, apply it to the GameObject that represents the Button. Under Target Graphic add the corresponding Object with the graphic. Under On Click() add an Event, put the gameobject that has your Attack Function in (None Object) and add the Attack function under Function.

here are some infos about how the button works: https://docs.unity3d.com/2018.3/Documentation/Manual/script-Button.html

edit: was also answered here Unity Button code not working

Upvotes: 0

Mohamed Awad
Mohamed Awad

Reputation: 640

try this one.

using UnityEngine;
using UnityEngine.UI;

public class Example : MonoBehaviour
{
    //Make sure to attach these Buttons in the Inspector
    public Button YourButton,

    void Start()
    {
        YourButton.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick(){ /// this method will active when press the button
       if (Time.time >= nextAttackTime)
       {
            Attack();
            nextAttackTime = Time.time + 2.5f / attackRate;
       }
    }
}

Upvotes: 1

Related Questions