i am 100% new to unity so i’m following a tutorial and in the tutorial the youtuber made this script for attacking that makes the character attack pressing f:
using System.Collections;
using UnityEngine;
public class playerattack : MonoBehaviour
{
void TaskOnClick()
{
Debug.Log("You have clicked the button!");
}
private bool attacking = false;
private float attackTimer = 0;
private float attackCd=0.3f;
public Collider2D attacktrigger;
private Animator anim;
void Awake()
{
anim = gameObject.GetComponent<Animator>();
attacktrigger.enabled = false;
}
void Update()
{
if (Input.GetKeyDown("f") && !attacking)
{
attacking = true;
attackTimer = attackCd;
attacktrigger.enabled = true;
}
if (attacking)
{
if (attackTimer > 0)
{
attackTimer -= Time.deltaTime;
}
else
{
attacking = false;
attacktrigger.enabled = false;
}
}
anim.SetBool("Attacking", attacking);
}
}
but i am making a mobile game how do i make it so that instead of pressing f i have to press an UI button?
Move the input code into a seperate function, drop a UI Button onto your screen, and on it’s events add your function (drag the behaviour with the script into the selectable objects then find it under your script - hard to explain)
Okay, you want to create a function for attacking and make it an OnClick event for your button. Here’s how to do that:
// Create this function below Update()
public void PlayerAttack()
{
if (Input.GetKeyDown("f") && !attacking)
{
attacking = true;
attackTimer = attackCd;
attacktrigger.enabled = true;
}
if (attacking)
{
if (attackTimer > 0)
{
attackTimer -= Time.deltaTime;
}
else
{
attacking = false;
attacktrigger.enabled = false;
}
}
anim.SetBool("Attacking", attacking);
}
You will delete everything inside of your update.
Now you need to add this function to your button. Click on the button in your hierarchy and in the inspector scroll down until you see this and click the + symbol:
This will open a field. Now your script the function is in will need to be on a game object within the hierarchy. You will drag that game object with the script attached into this field:
Next you want to click this:
This will bring up a menu and you want to hover your mouse over your script and it will open options. You will select the function you made. In this example, the script was named LevelManager and the function its accessing is LoadLevel, which must be a public function inside of the LevelManager script for it to show up.