- Home /
how would I set up a regain health ui button
in my tower defense game I want to have a ui button that player can press with a cool down that will add a extra live to the total live in the level for ex: player has one life left they click on the regain health button on the screen to go from one life to two lives and than the button has a 5 second cool down I don't know where to begin with this one as I'm fairly new with scripts so can somebody point in the right direction. I know how to make a button in unity and I know how the on click section works I just don't know how I would type up the script for it. if have scripts that have functions that attribute to my lives system if need to show that off let me know. I will show this script as it says once the enemy reaches that end of the waypoints to destroy the enemy game object (Itself) and reduce the lives number by one.
this is my enemy movement script it has my lives system in it under endPath
using System.Collections;
using UnityEngine;
[RequireComponent(typeof(Enemy))]
public class EnemyMovement : MonoBehaviour
{
private Enemy enemy;
private Transform target;
private int waypointIndex = 0;
// Start is called before the first frame update
void Start()
{
target = Waypoints.points[0];
enemy = GetComponent<Enemy>();
}
// Update is called once per frame
void Update()
{
Vector3 dir = target.position - transform.position;
transform.Translate(dir.normalized * enemy.speed * Time.deltaTime, Space.World);
if (Vector3.Distance(transform.position, target.position) <= 0.2f)
{
GetNextWaypoint();
}
}
void GetNextWaypoint()
{
if(waypointIndex >= Waypoints.points.Length - 1)
{
EndPath();
return;
}
waypointIndex++;
target = Waypoints.points[waypointIndex];
}
void EndPath()
{
PlayerStats.Lives--;
Destroy(gameObject);
WaveSpawner.EnemiesAlive--;
}
}
Answer by Reid_Taylor · Sep 03, 2020 at 06:47 PM
While I am sort-of confused why you gave the enemy script and not the player script I'll try my best :).
So let's say your player script looks like this:
public class Player : MonoBehaviour
{
public int lives = 10;
public void Hurt(int amount)
{
lives -= amount;
}
public void Heal(int amount)
{
lives += amount;
}
}
I would morph this into this:
public class Player : MonoBehaviour
{
public int lives = 10;
private float healTimer = 0;
public float timeBetweenHeals = 10;
public float amountToHealOnClick = 1;
private void Start()
{
healTimer = timeBetweenHeals;
}
private void Update()
{
if (healTimer > 0)
{
healTimer -= Time.deltaTime;
}
}
public void Hurt(int amount)
{
lives -= amount;
}
public void Heal(int amount)
{
lives += amount;
}
public void HealOnClick()
{
if (healTimer > 0)
return;
lives += amountToHealOnClick;
healTimer = timeBetweenHeals;
}
}
Then assign the HealOnClick()
function to your button. And I should note that this doesn't do any visuals but if you wanted to you could add radial fill image and set its fill amount in update to healTimer / timeBetweenHeals
.
Hope this helps!