Here is base concept:
-I want to display health by hearts like this

in WEB I usually solve this with css repeat-x and width but I’m sure GameDev has another solution. Something like
for(I=1; I<healthcount; I++){
displayOneHeart();
}
The main trouble is I have no idea how to do it in unity and also no idea with search engine query for the right result match. That’s why I created this thread, sorry if it is duplicate (and for my eng to).
For each hit, do you lose a heart? If so you would create a loop and disabled at will.
Try this (Assuming Right → Left to reduce and Left → Right to increase):
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Example : MonoBehaviour {
[SerializeField]
List<GameObject> hearts = new List<GameObject>();
public void ReduceHeartsBy(int amount) {
for(int i = this.hearts.Count - 1, disabled = 0; i > 0; i--) {
if(this.hearts[i] != null) {
if(disabled < amount) {
if(this.hearts[i].activeSelf == true) {
this.hearts[i].SetActive(false);
disabled++;
}
}
}
}
}
public void IncreaseHeartsBy(int amount) {
for(int i = 0, enabled = 0; i < this.hearts.Count; i++) {
if(this.hearts[i] != null) {
if(enabled < amount) {
if(this.hearts[i].activeSelf == false) {
this.hearts[i].SetActive(true);
enabled++;
}
}
}
}
}
}
1 Like
Heres a quick example
using UnityEngine;
using System.Collections;
public class ShowHearts : MonoBehaviour
{
//First option, have them in the scene but disabled, enable them via script
public GameObject[] hearts; //Assign the hearts here, preferrably in order to enable
public int amountToShow = 0; //self explanatory
void Start()
{
foreach(GameObject heart in hearts) //For every heart, do something
{
heart.SetActive(false); //Disable all the hearts for now
}
}
void Update()
{
if(Input.GetKeyDown(KeyCode.Space)) //if you press SPACEBAR
Show(); //Show any that arent already shown
if(Input.GetKeyDown(KeyCode.W)) //if you press W
amountToShow++; //add 1 to amountToShow so we can enable another one
}
void Show()
{
for(int i = 0;i < amountToShow;i++)
{
hearts[i].SetActive(true);
}
}
}
1 Like