- Home /
How to have player gain health on button click
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Heart : MonoBehaviour {
public void onClick()
{
var health = GetComponent<Health>();
if (HeartTextScript.heartAmount >= 0)
{
HeartTextScript.heartAmount -= 1;
if (health != null)
{
health.currentHealth += 50;
}
}
}
}
How do I make it so when I click a button my player will gain health. Thanks!
Comment
Answer by toddisarockstar · Oct 28, 2018 at 01:30 AM
void update repeats once per frame. this is a good place to detect inputs with unity.
public class Heart : MonoBehaviour {
void Update () {
if (Input.GetKeyDown (KeyCode.H)) {
// the key H was pressed
onClick();
}
if (Input.GetMouseButtonDown (0)) {
//mouse clicked
onClick();
}
}
public void onClick()
{
var health = GetComponent<Health>();
if (HeartTextScript.heartAmount >= 0)
{
HeartTextScript.heartAmount -= 1;
if (health != null)
{
health.currentHealth += 50;
}
}
}
}