1

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;
        }
    }
  • 1
    Does this answer your question? [How to detect click/touch events on UI and GameObjects](https://stackoverflow.com/questions/41391708/how-to-detect-click-touch-events-on-ui-and-gameobjects) – nkazz Nov 05 '20 at 20:09

2 Answers2

1

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;
       }
    }
}
Mohamed Awad
  • 630
  • 1
  • 6
  • 14
0

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

nkazz
  • 488
  • 1
  • 8
  • 13