- Home /
Health Bar/Hearts?
So, I've been researching for WEEKS on end how to make a working heart system for a 2D Unity platformer I'm doing. Only problem is, I'm a total noob just about all things Unity here, and I'm a wee bit new to coding (though I understand C# and how it works). The biggest problem I've been having is using a health system where when the player is hit, a heart vanishes. While I'm absolutely aware that there's already a thread on the topic, most of it suggests that I use GUI, which I absolutely hate, and the code that doesn't suggest I use GUI settings is a bit too complicated for the timeframe I have, and I run the risk of ruining my game. I know I'm asking a lot, and I don't expect anyone to just WRITE THE CODE for me, I just need a bit of a for-dummies rundown on how this all works.
Also for clarification, I'll note that the health code is in a separate script from the player controller code, if that happens to be relevant.
Answer by OrionGamesInc · Jan 16, 2018 at 05:22 PM
This is definitely not perfect, but it may be useful to learn how the sprite fill system works in Unity.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Player : MonoBehaviour {
[Header("Player")]
public Player player; //the player object that holds the player script
[Header("Stats")]
public int maxHealth; //total amount of hearts
public int health; //current number of hearts
[Header("UI")]
public Sprite healthUI; //use an image of four hearts next to eachother, spacing will help make it look better
void Update(){ //change the value of your sprite using a horizontal fill, space the hearts out so that 1 includes only 1 heart and so on
maxHealth = player.maxHealth;
health = player.health;
healthUI.fillAmount = health / maxHealth; //will always return a decimal for percentage
}
}
EDIT: I just read your comment and you can include a reference to the Health object if the Player script is attached to your player, just drag it into the slot in the inspector.
Although, quick noob comment here: When you say it's in the Player class, you mean I should put it in the character controller script, right? (Sorry if that's redundant of me to ask, just wanna make sure I don't wreck my code by putting it in the wrong place)
updated the answer, hopefully that helps. if not i'll try to help out more
thank you for being patient w/ me! it makes more sense to me now.
Answer by Constantin_d · Jun 10, 2020 at 01:37 PM
tutorial about how to make a heart bar system only using sprites and a small amount of code:
https://www.youtube.com/watch?v=Dg-6qoZ2JqI&list=PLyz_wKnxtoQO0Tf3koreC4gJtFv4213yQ