- Home /
Question by
GrayW01f · Feb 13, 2021 at 07:36 PM ·
c#top down shooter
Health Regen Button
Hi! I have A working Inventory system and health system, but I can't figure out how to make it so the health button regens health here's my code:
Health:
`using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI;
public class Health : MonoBehaviour { public int health; public int numOfHearts;
public Image[] hearts;
public Sprite fullHeart;
public Sprite emptyHeart;
private void Start() {
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Enemy"))
{
health -= 1;
}
}
void Update()
{
if (health > numOfHearts)
{
health = numOfHearts;
}
if (health < 1)
{
Destroy(this.gameObject);
}
for (int i = 0; i < hearts.Length; i++)
{
if (i < health)
{
hearts[i].sprite = fullHeart;
}
else
{
hearts[i].sprite = emptyHeart;
}
if(i < numOfHearts)
{
hearts[i].enabled = true;
}
else
{
hearts[i].enabled = false;
}
}
}
}
Button:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthButton : MonoBehaviour
{
public GameObject effect;
private Transform player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
}
// Update is called once per frame
public void Use()
{
Instantiate(effect, player.position, Quaternion.identity);
Destroy(gameObject);
}
}
screenshot-10.png
(324.4 kB)
screenshot-12.png
(375.6 kB)
Comment
Answer by ShuaG · Feb 13, 2021 at 08:40 PM
make your health script into an instance (so you can access it from a different script) by writing public static Health instance;
void Awake ()
{
instance=this
}
and then in the use function in the button script add
Health.instance.health++;
which accesses the health scripts variable "health" and adds a heart.
try this
Your answer
![](https://koobas.hobune.stream/wayback/20220613025122im_/https://answers.unity.com/themes/thub/images/avi.jpg)