I can really appreciate that you paused the video and asked us to figure out how to code the restore health function. This really helped me understand what I was learning!
For anyone whose images looked see-through in the UI, you can change that via the Inspector -> Image -> Color -> Set Alpha to maximum for 0% translucency.
This whole series is so damn good. Thanks for making it freely available :D For anyone trying to code along with him I would recommend turning the speed of the video down to 0.5, it's much easier to keep up and it also makes the narrator sound completely drunk.
Thank you, I got it integrated pretty quickly in my game and also learned about many cool ui based elements :) even made custom health bar stuff in blender, super flexible :D +sub
Great Videos So Far! I noticed from the previous video, from creating the input manager for the player character. It will throw an error code when using if (Input.GetKeyDown(KeyCode.A)); I just removed it and will use the player damage and health to continue! Thank you!
hey dude sorry if this is a dumb question ima pro noobie, but what u mean u just used the playerdamage and health to continue? have u written scripts for attacks and healthkits?
@@torbenkramm2725 He´s using his healtbar script, but wont test it out, cause its based on old input system. He could test it and ignore the error (mean its a yellow warning.)
Out of curiosity, at 12:38, for line 55, what's the difference between doing 'Mathf.Lerp(fillF, backHealthBar,fillAmount, percentComplete)', and 'Mathf.Lerp(fillF, hFraction, percentComplete)'? Is there a reason to use one over the other, or? Both seems to work, but I'm not sure if there's a reason to use the first more than the second
Great tutorial! I have one question as to how i can delay the chip from going off immediately, like a 0.5 second delay before it starts following the health
Thanks heaps! To create a delay you will need to add a new variable at the top of the class. private float delayTimer; Then in update after we check the difference between our fillamount and hFraction we can Increment the timer. delayTimer +=Time.deltaTime; Then use an if statement to check if (delayTimer > 0.5f) { }.... Then take all the logic that does the keep and updates our UI and pop it into the if statement... And it's very important that you reset delayTimer inside TakeDamage and RestoreHealth otherwise it won't work after the first time. Hope this Helps !! :)
@@NattyGameDev Hi, thanks for the tutorial ! but i dont know how to reset delayTimer inside TakeDamage, the delay only work for the first time and wont work after that.
I dont know why but I followed everything but my if (Input.GetKeyDown(KeyCode.A)) doesnt seem to work as when pressing A nothing happens no console info no healthbar movement. Any help?
After writing the code from 6:37, I keep getting this error "InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings. UnityEngine.Input.GetKeyDown (UnityEngine.KeyCode key) (at :0)"
i have this problem Assets\Scripts\PlayerHealth.cs(52,22): error CS0136: A local or parameter named 'percentComplete' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
everytime when i try to add my playerhealth script to my player it gives me the error: can't add script component playerhealth because the script class cannot be found
Rename the main class in the script (The first public class you will see in the script), it should have the same name with the name you called the script.
how can i make it not move while getting damaged and then after a while of not beng damaged it goes back to the front health fill amount or sth never mind i did it was preety simple here is the code i wrote using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.UI.ProceduralImage; public class HealthController : MonoBehaviour { public static HealthController Instance; void Awake() { if (Instance == null) Instance = this; else { Destroy(gameObject); return; } } [Header("References")] [SerializeField] private ProceduralImage frontHealthBar; [SerializeField] private ProceduralImage backHealthBar; [Header("Health Settings")] [SerializeField] private float health; [SerializeField] private float maxHealth = 100f; [Header("Animation")] [SerializeField] private Color restoreHealthColor; [SerializeField] private Color damageHealthColor; [SerializeField] public float chipSpeed = 2f; [SerializeField] public float chipDelay = 2f; private float lerpTimer; private float waitTime; private void Start() { health = maxHealth; } private void Update() { health = Mathf.Clamp(health, 0, maxHealth); UpdateHealthUI(); } public void UpdateHealthUI() { Debug.Log(health); float fillF = frontHealthBar.fillAmount; float fillB = backHealthBar.fillAmount; float hFraction = health / maxHealth; waitTime += Time.deltaTime; if (fillB > hFraction) { frontHealthBar.fillAmount = hFraction; if (waitTime > chipDelay) { backHealthBar.color = damageHealthColor; lerpTimer += Time.deltaTime; float percentComplete = lerpTimer / chipSpeed; percentComplete = percentComplete * percentComplete; backHealthBar.fillAmount = Mathf.Lerp(fillB, hFraction, percentComplete); } } if (fillF < hFraction) { backHealthBar.color = restoreHealthColor; if (waitTime > chipDelay) { backHealthBar.fillAmount = hFraction; lerpTimer += Time.deltaTime; float percentComplete = lerpTimer / chipSpeed; percentComplete = percentComplete * percentComplete; frontHealthBar.fillAmount = Mathf.Lerp(fillF, backHealthBar.fillAmount, percentComplete); } } } public void TakeDamage(float amount) { health -= amount; lerpTimer = 0; waitTime = 0; } public void RestoreHealth(float amount) { health += amount; lerpTimer = 0; waitTime = 0; } }
@@NattyGameDev I like your content. I am still learning about Unity and programming and your content is look like is between beginner and intermediate. I haven't seen much content like that. The transition from beginner to intermediate it is very complicated and this helps a lot.
@@GreenGnoblin that's my goal! I aim to produce tutorials that you can use to take that next step in the development process. The next video in the series will be abit more advanced but I am working hard to make it nice and easy to understand ! :)
@@NattyGameDev Do not worry. The only one people can progress and exapand their skills are by challenges and experience. Go for it! I will be waiting the next video.
could someone help me out? I cant figure out how to import the assets into my project. I used the link and downloaded them but Im unable to import the package and I have no idea why
hi, The background health color is changed permanently without reversing into the original. May I know why. For ex: In decreasing the health, the background turns to red, decrease to follow the front, but the red stays after that, and not turning back to gray color
So we don't need to change the background colour back to Grey because it is usually covered by our front health back, so the only time we see the back health bar is when we have changed it to either red or green.. :) hope this helps!
My problem now was, once the character received any damage, the front healthbar instantly goes to 0 and followed by the backhealthbar. But the value of the character health is reduced accordingly. Im really confused
Maybe you used int instead of float for the Health and maxHealth values? I did this at first and had the same problem but after changing to float (like in the video) it worked
guys i have like 12 compile errors can you guys correct it because it look identicle to his using System.Collections; using System.Collections.Generic; using UnityEngine.UI; public class NewBehaviourScript : MonoBehaviour { private float health; private float lerptimer; public float maxhealth 100f; public float chipspeed 2f; public image fronthealthbar; public image backhealthbar; // Start is called before the first frame update void Start() { health = maxhealth; } // Update is called once per frame void Update() { health = mathf.Clamp(health, 0, maxhealth); UpdateHealthUI (); if (input.Keydowncode(Keycode a)); { Takedamage (Random.Range(5,10)); } } public void UpdateHealthUI; {
Debug.log(health); } public void Takedamage (float damage); { health -= damage; lerptimer 0f; } }
I don't know if this will help anyone now but you were missing a bunch of capitals which I believe are essential. E.g. maxHealth; not maxhealth; (I am rather new to untiy too, if this doesn't help, I don't know)
I might need abit more info in order to help ! The health bar should change when you press the key that you have assigned for TakeDamage or RestoreHealth.
How would I make it so an enemy attack does damage to the player, instead of pressing B? public class enemyAttack : MonoBehaviour { public ParticleSystem ps; public int damage = -20; public float TimerForNextAttack, Cooldown; void Start() { } void Update() { if (TimerForNextAttack > 0) { TimerForNextAttack -= Time.deltaTime; } else if (TimerForNextAttack
On my main character, (A Bird) I have attached your HealthBar script., that allows you to press keys to make the bar go Up or Down., I also have a separate player script that controls movement, collisions, etc, etc... also attached to the Bird... Wwithin this second script I have the following which successfully makes the health go down on practically any collision, so it's doing a function contained in Script A (Healthbar) from script B (player controls) - and all works OK.. void OnCollisionEnter2D(Collision2D collision) { GetComponent().TakeDamage(2); StartCoroutine(ResetAfterDelay()); FindObjectOfType().Play("CrateSmash");
} I want it that if you collide with an apple, it's adds health. I have a script attracted to my apple object, and within it contains the following -: IEnumerator Die() { _hasBeenEaten = true; ScoreScript.scoreValue += 750; ***This works GetComponent().sprite = _eatenSprite; ***This works print("An Apple Has Been Eaten"); ***This works FindObjectOfType().Play("Crunch"); ***This works _particleSystem.Play(); ***This works yield return new WaitForSeconds(1); ***This works GetComponent().RestoreHealth(25); This will not restore health
So I believe what is happening is that your trying to "get the component" of BirdHealth on the apple.. however the apple doesn't have a BirdHealth component.. that will be located on your player... So you will need to store the BirdHealth script on a collision.... At the top of the class.. use private BirdHealth birdHealth;. And in you OnCollision function use birdHealth = other.GetComponent(); Then where you want to restore health you can use. birdHealth.RestoreHealth(25); So your creating a variable and then storing the BirdHealth in the script... Then you have access to all its functions an variables :D
@@NattyGameDev OK Ill give that a go... I did previously create a copy of the entire health system and applied to to various objects to no avail, but yeah I'll give that other.xxxx a go.... I also tried GetComponent().TakeDamage(20); in other scripts and it didn't work. The GetComponent().TakeDamage(20); is only working in my other script because the health script is attached to the same object
@@PeterJohnson76 that's correct ! If your just using "GetComponent....". It will only look at the scripts on *that* gameobject. ..If you would like you can add me on twitter @Gnats_Reserve and you can send me the scripts there and we will work it out ! :D
Hey! thanks for the question :) You can do this by; -creating a new text object (or textmesh) call it something like "healthText" -creating a public property for this in your health script... -drag the text object onto the health script in the inspector. -in your UpdateHealthUI() method assign healthText.text = health; or even healthText.text = health + "/" + maxHealth; Hope this helps!
@@NattyGameDev I can`t drag the "healthText" into the public property, that's why I want to ask which property I need to use I used: public text healthText;
Yeah! I will be doing the second one very soon ! I started another series but I will move this one up in the list :) Thanks for watching and commenting !
@@NattyGameDev welcome, it's a great looking health system. What's the best way to add health up or down within my game levels within various functions... I also found when adding the health bar to other levels the script wasent woking, despite it being bonded to my main characters prefab.
@@PeterJohnson76 So in regards to adding health up or down, You will always need a reference to the player prefab to call the function from another script. You can do this by: •Raycasting (if an enemy is shooting the player), •Colliders (for physical impact attacks and Picking up healthpacks.), •By tagging the player prefab with "Player" and using GameObject.FindObjectWithTag("Player"); Then after you have a reference to the player prefab you can call GetComponent().TakeDamage(10); / .RestoreHealth(10); and regarding the health system working across scenes, are you moving from one scene to another? or just loading a different level, with the UI elements in that scene? You can try parent the canvas to the player prefab. and also try using DontDestroyOnLoad on the PlayerHealth script. Let me know if you have any other questions! Hope this helps! :)
@@NattyGameDev Thanks, but I'm still having issues accessing PlayerHealth.cs and its functions from other scripts. How can I decrease the health from within any one of my other C# scripts.... I think I need help creating the reference.
@@PeterJohnson76 Sure thing! :) how are you wanting to damage the player, from a distance? up close? or over time? what is the method that you want to use to damage the player?
Am I the only one bothered by how he complicates his usage of Angle Brackets for no reason? Like just press "{" and then Enter, that's it, Visual Studio will fo the rest
The HealthBar works great, but when my Enemy Damage the Player the HealthBar dont work. (I don´t no how to fix it because im new in Coding Anyone can help me?) I had override the Healh Script to but it doesn´t Work. My override Health-Script: using System.Runtime.InteropServices; using System.Security.Permissions; using System.Threading; using UnityEngine.UI; using UnityEngine; public class PlayerHealth : MonoBehaviour { private float Health; private float lerpTimer; public float maxHealth = 100f; public float chipSpeed = 2f; public Image frontHealthbar; public Image backHealthbar; public GameObject DeathUI; void Start() { Health = maxHealth; } void Update() { Health = Mathf.Clamp(Health, 0, maxHealth); UpdateHealthUI(); // if (Input.GetKeyDown(KeyCode.A)) // { // TakeDamage(Random.Range(5, 10)); // } // if (Input.GetKeyDown(KeyCode.S)) // { // RestorHealth(Random.Range(5, 10)); } public void GameOver() { UnityEngine.Debug.Log("uIsdead"); DeathUI.SetActive(true); Time.timeScale = 0f; } public void UpdateHealthUI() { Debug.Log(Health); float fillF = frontHealthbar.fillAmount; float fillB = backHealthbar.fillAmount; float hFraction = Health / maxHealth; if(fillB > hFraction) { frontHealthbar.fillAmount = hFraction; backHealthbar.color = Color.red; lerpTimer += Time.deltaTime; float percentComplete = lerpTimer / chipSpeed; backHealthbar.fillAmount = Mathf.Lerp(fillB, hFraction, percentComplete); } if(fillF < hFraction) { backHealthbar.color = Color.green; backHealthbar.fillAmount = hFraction; lerpTimer += Time.deltaTime; float percentComplete = lerpTimer / chipSpeed; percentComplete = percentComplete * percentComplete; frontHealthbar.fillAmount = Mathf.Lerp(fillF, backHealthbar.fillAmount, percentComplete); } } public void TakeDamage(float damage) { Health -= damage; lerpTimer = 0f; } public void RestorHealth(float healAmount) { Health += healAmount; lerpTimer = 0f; } }
@@NattyGameDev Thsnks for the FeedBack, I had a public float whit a Attack Range Damage usw. (when the player in Range) the Enemy attack him whit this Code:" void Attack() { FindObjectOfType().maxHealth -= Damage; if (FindObjectOfType().maxHealth
@FyMa2618 so you don't want to change the maxHealth of the player you will want to change the *health* variable.. changing the max health won't affect the size of health bar (you can change the max health if you are leveling up.. which we will do in the next video) And also.. using FindObjectOfType is an expensive function to call each time you want to attack. So at the top of the class create a variable to store player health. "private PlayerHealth playerHealth;". And in start assign the player once.. using playerHealth = Gameobject.FindObjectWithTag("Player") GetCompnent();. And make sure that you tag the player. Then you should have the reference to the player.. and you can change the health value.. Thanks for watching !! And I hope this helps ! Message me if you have any other questions ! :D
@FyMa2618 also ! Just remembered you dont need to hardcode changing the health! So instead just use the public TakeDamage(x) function. And pass in the number that you want to damage the player where the x is .. eg:. TakeDamage(20);.... So with what I said in the last comment the full line would be... playerHealth.TakeDamage(20);
@@NattyGameDev Thank´s you, but i had made all what you rode done but it came a Error called:";". When you need the Changed Code: using UnityEngine; public class EnemyAttack : MonoBehaviour { private PlayerHealth playerHealth; public float Range = 1f; public Transform AttackPoint; public LayerMask PlayerLayer; bool PlayerCheck; public float Damage = 15f; public float AttackSpeed = 1f; float nextTimeToFire = 0f; void Start() { playerHealth = Gameobject.FindObjectWithTag("Player") GetCompnent(); } void Update() { PlayerCheck = Physics.CheckSphere(AttackPoint.position, Range, PlayerLayer); if (PlayerCheck == true && Time.time >= nextTimeToFire) { Attack(); nextTimeToFire = Time.time + 1f / AttackSpeed; } } void Attack() { FindObjectOfType().maxHealth -= Damage; if (FindObjectOfType().maxHealth
@@Megalilalol1 So unfortunately this cant be done using the "filled" Image type to do this.. you would need this using a 9 sided sprite, or with a mask that moves across from the right-hand side of the health bar.
@@Megalilalol1 I'll have a look at what is possible with a 9 sided sprite, you may be able to do it without worrying about a sprite and the backwards math :P
Any reason why you don't include the source code in the description? As an intermediate Unity user I don't need the hand guided tutorial but just need a headstart on the logic and code. I'm going to pause the video and copy the code anyway, so why not just include it?
@@NattyGameDev So you are locking copying and pasting behind a paywall? Don't get me wrong it is great to support creators but why should I pay you to allow me to copy and paste your code that you are already willing to share in a video? I hope this doesn't come off wrong as I really appreciate content creators and what they provide. However I'm a strong believer in open source .
@@spacedog2980 Absolutely! The Patreon will be more for access to Project files Eg : 3D Models, Unity Scenes, Animations, Textures, Audio Clips, So any files related to the tutorial videos + other Patreon exclusive assets. The tutorials are here to help people learn how to code these gameplay systems, also, give the freedom to create your own game using those systems. It is educational content, and I feel like Copy/Paste is not the best approach to learning. We all need to go through process of encountering bugs and researching how to fix them. The "paywall" will be for those who want to cross reference with my files (Scene and Scripts), along with other Patreon benefits as well. I am striving to provide content on a similar caliber to that of SkillShare/Udemy courses, without the need to pay for access to the video content :) This won't be launching for a little bit yet, and won't affect the way in which the tutorials are presented on UA-cam. Hope this addresses any concerns you have! :)
@@NattyGameDev Awesome. Thanks for clearing that up. I agree on the copy/paste approach not being the best for learning. It is definitely better to go through the motions so you understand what's going on. In my case I already had an understanding of what needs to be done based on your description at the start of the video. So having access to the code straight away would have saved me some time. That being said, I enjoyed the video and it is indeed a good tutorial. I appreciate your response.
Hi Natty, I need this but with a 3D enemy attacking the FPS Character Controller at close range, and the health bar goes down like 20% with each attack can you make it for me?
My health bar isn't changing when I press the buttons that I set for it to change, and this: NullReferenceException: Object reference not set to an instance of an object PlayerHealth.UpdateHealthUI () (at Assets/Scripts/PlayerHealth.cs:37) PlayerHealth.Update () (at Assets/Scripts/PlayerHealth.cs:24) keeps popping up in the debug console. What can I do to fix it?
Absolutely great tutorial. Have been following through since your first fps tutorial and have found very little issues. Especially as I'm a complete beginner. Also I'm following this 3yrs later and still pretty solid. However I have come across an error which I no is an easy fix, just like I said am a complete novice to this and think it's just an updated version of unity I'm using. But in the code for the health bar I'm getting a null reference exception error. Object not set to an instance of an object. Health bar.UpdateHealthUI. it's at health bar.cs 39. I'm really sorry I no this is basic but only been learning for a week.
if you can't drag and drop them onto the panel -> Change each image texture type to sprite/2D/UI
Hello from 21.3.5.f1
Thank you
thanks
Thanks 1000000000000 times man!
How do you do it?
THANK YOU
I can really appreciate that you paused the video and asked us to figure out how to code the restore health function. This really helped me understand what I was learning!
For anyone whose images looked see-through in the UI, you can change that via the Inspector -> Image -> Color -> Set Alpha to maximum for 0% translucency.
I've never found a series that has helped me so much in Unity. Keep up the good work!
So true
This is one of the best explanations regarding healthbars in unity imo. Good videos man, thanks!
This whole series is so damn good. Thanks for making it freely available :D
For anyone trying to code along with him I would recommend turning the speed of the video down to 0.5, it's much easier to keep up and it also makes the narrator sound completely drunk.
very true lol🤣
I hav it att 2
@@avospelar8899 that's always an option, of course
I wish I had a job so that I had money to support your channel. You deserve all good the things that are going your way
I have seen so many tutorials but this one Is so good This channel is so so so underrated
Excellent video - your presentation is very clear and easy to follow. Thanks
The best tutorial ever! I wonder why you still haven't reached 1 mil.
Thank you, I got it integrated pretty quickly in my game and also learned about many cool ui based elements :) even made custom health bar stuff in blender, super flexible :D +sub
this was such a good video, this helped me out so much! it's something super subtle but is good game feel for sure! thank you!
Thank you for the tutorial! It is very helpful.
Looks really cool
Thank you! Exactly what I was looking for. You earned new subscriber :)
everything works great!, but when I'm adding heals I dont see the green color going up, just the normal health bar
Great Videos So Far!
I noticed from the previous video, from creating the input manager for the player character. It will throw an error code when using if (Input.GetKeyDown(KeyCode.A));
I just removed it and will use the player damage and health to continue!
Thank you!
hey dude sorry if this is a dumb question ima pro noobie, but what u mean u just used the playerdamage and health to continue? have u written scripts for attacks and healthkits?
@@torbenkramm2725 He´s using his healtbar script, but wont test it out, cause its based on old input system. He could test it and ignore the error (mean its a yellow warning.)
Out of curiosity, at 12:38, for line 55, what's the difference between doing 'Mathf.Lerp(fillF, backHealthBar,fillAmount, percentComplete)', and 'Mathf.Lerp(fillF, hFraction, percentComplete)'? Is there a reason to use one over the other, or? Both seems to work, but I'm not sure if there's a reason to use the first more than the second
dude your videos are so great. thank you so much
Very useful... thank you and i look forward to your great videos
took me way more time that it should have , as much i expected , im making progress i guess, code looks less scary.
isn't that lerp timer variable keep adding?
Yes, but i think its okay, thats how Update() doing anyway, called every frame
Really helpful, would recommend 10/10
Great tutorial! I have one question as to how i can delay the chip from going off immediately, like a 0.5 second delay before it starts following the health
Thanks heaps! To create a delay you will need to add a new variable at the top of the class.
private float delayTimer;
Then in update after we check the difference between our fillamount and hFraction we can Increment the timer.
delayTimer +=Time.deltaTime;
Then use an if statement to check
if (delayTimer > 0.5f) { }....
Then take all the logic that does the keep and updates our UI and pop it into the if statement...
And it's very important that you reset delayTimer inside TakeDamage and RestoreHealth otherwise it won't work after the first time.
Hope this Helps !! :)
@@NattyGameDev great stuff, thanks for this
@@NattyGameDev Hi, thanks for the tutorial ! but i dont know how to reset delayTimer inside TakeDamage, the delay only work for the first time and wont work after that.
@@nkxk26 maybe set it to 0f same as lerpTimer ;-)
I dont know why but I followed everything but my if (Input.GetKeyDown(KeyCode.A)) doesnt seem to work as when pressing A nothing happens no console info no healthbar movement. Any help?
After writing the code from 6:37, I keep getting this error "InvalidOperationException: You are trying to read Input using the UnityEngine.Input class, but you have switched active Input handling to Input System package in Player Settings.
UnityEngine.Input.GetKeyDown (UnityEngine.KeyCode key) (at :0)"
its becouse you are using the new unity input system and he is using the legacy one (the old one).
i have this problem Assets\Scripts\PlayerHealth.cs(52,22): error CS0136: A local or parameter named 'percentComplete' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
everytime when i try to add my playerhealth script to my player it gives me the error: can't add script component playerhealth because the script class cannot be found
Rename the main class in the script (The first public class you will see in the script), it should have the same name with the name you called the script.
This helped me immensely, thank you!
I am super happy this helped! Thank you for watching :)
Thank You for great tutorial
keep up the good work
Nicely done.
how can i make it not move while getting damaged and then after a while of not beng damaged it goes back to the front health fill amount or sth
never mind i did it was preety simple here is the code i wrote
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UI.ProceduralImage;
public class HealthController : MonoBehaviour
{
public static HealthController Instance;
void Awake()
{
if (Instance == null) Instance = this;
else
{
Destroy(gameObject);
return;
}
}
[Header("References")]
[SerializeField] private ProceduralImage frontHealthBar;
[SerializeField] private ProceduralImage backHealthBar;
[Header("Health Settings")]
[SerializeField] private float health;
[SerializeField] private float maxHealth = 100f;
[Header("Animation")]
[SerializeField] private Color restoreHealthColor;
[SerializeField] private Color damageHealthColor;
[SerializeField] public float chipSpeed = 2f;
[SerializeField] public float chipDelay = 2f;
private float lerpTimer;
private float waitTime;
private void Start()
{
health = maxHealth;
}
private void Update()
{
health = Mathf.Clamp(health, 0, maxHealth);
UpdateHealthUI();
}
public void UpdateHealthUI()
{
Debug.Log(health);
float fillF = frontHealthBar.fillAmount;
float fillB = backHealthBar.fillAmount;
float hFraction = health / maxHealth;
waitTime += Time.deltaTime;
if (fillB > hFraction)
{
frontHealthBar.fillAmount = hFraction;
if (waitTime > chipDelay)
{
backHealthBar.color = damageHealthColor;
lerpTimer += Time.deltaTime;
float percentComplete = lerpTimer / chipSpeed;
percentComplete = percentComplete * percentComplete;
backHealthBar.fillAmount = Mathf.Lerp(fillB, hFraction, percentComplete);
}
}
if (fillF < hFraction)
{
backHealthBar.color = restoreHealthColor;
if (waitTime > chipDelay)
{
backHealthBar.fillAmount = hFraction;
lerpTimer += Time.deltaTime;
float percentComplete = lerpTimer / chipSpeed;
percentComplete = percentComplete * percentComplete;
frontHealthBar.fillAmount = Mathf.Lerp(fillF, backHealthBar.fillAmount, percentComplete);
}
}
}
public void TakeDamage(float amount)
{
health -= amount;
lerpTimer = 0;
waitTime = 0;
}
public void RestoreHealth(float amount)
{
health += amount;
lerpTimer = 0;
waitTime = 0;
}
}
Is there a way to do the Lerp of the back health bar outside of the Update function? I'm trying with coroutines but can't figure how to do it.
Hi sorry for the late reply! It's been a super busy week! I will have a look into this for you and get back to you as soon as I can!
Very nice video! You got a new subscriber. Keep up the good work!
Thanks so much !
@@NattyGameDev I like your content. I am still learning about Unity and programming and your content is look like is between beginner and intermediate. I haven't seen much content like that. The transition from beginner to intermediate it is very complicated and this helps a lot.
@@GreenGnoblin that's my goal! I aim to produce tutorials that you can use to take that next step in the development process. The next video in the series will be abit more advanced but I am working hard to make it nice and easy to understand ! :)
@@NattyGameDev Do not worry. The only one people can progress and exapand their skills are by challenges and experience. Go for it! I will be waiting the next video.
how does this work in a game tho, I've tried to put it in a onTriggerEnter, and the backhealth doesn't want to follow the front healthbar
Thanks. Everything is work and stylish)
couldn't find the requested platform texture settings help
This is excellent! Thank you so much! New suscriber! of course!
just a question , what should i do to stop number increasing in console , right
could someone help me out? I cant figure out how to import the assets into my project. I used the link and downloaded them but Im unable to import the package and I have no idea why
Where is the image type dropdown I don't see it
Can you start adding a link so you can copy and past all the code
yo, nice health bar and thanks for recommendation))
Thanks, you saved me
why when i imported my images they are faded
Thank for your helpful tip
S+ tier tutorial
hi,
The background health color is changed permanently without reversing into the original. May I know why.
For ex: In decreasing the health, the background turns to red, decrease to follow the front, but the red stays after that, and not turning back to gray color
So we don't need to change the background colour back to Grey because it is usually covered by our front health back, so the only time we see the back health bar is when we have changed it to either red or green.. :) hope this helps!
how did you add the frame onto the panel as the background? It wont let me drag and drop anything onto it
I figured it out. For anyone who experienced the same thing, listen to the beggining again where he says to make sure theyre a "sprite"
restore health not working bro
Where can i get the heartIcon?
Just what I wanted....thanks
My problem now was, once the character received any damage, the front healthbar instantly goes to 0 and followed by the backhealthbar. But the value of the character health is reduced accordingly. Im really confused
Maybe you used int instead of float for the Health and maxHealth values? I did this at first and had the same problem but after changing to float (like in the video) it worked
can anyone drop the code?
guys i have like 12 compile errors can you guys correct it because it look identicle to his
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
private float health;
private float lerptimer;
public float maxhealth 100f;
public float chipspeed 2f;
public image fronthealthbar;
public image backhealthbar;
// Start is called before the first frame update
void Start()
{
health = maxhealth;
}
// Update is called once per frame
void Update()
{
health = mathf.Clamp(health, 0, maxhealth);
UpdateHealthUI ();
if (input.Keydowncode(Keycode a));
{
Takedamage (Random.Range(5,10));
}
}
public void UpdateHealthUI;
{
Debug.log(health);
}
public void Takedamage (float damage);
{
health -= damage;
lerptimer 0f;
}
}
I don't know if this will help anyone now but you were missing a bunch of capitals which I believe are essential. E.g. maxHealth; not maxhealth; (I am rather new to untiy too, if this doesn't help, I don't know)
I can't drag and drop a frame onto the source image in the panel
How do I fix it?
Have you made the frame a sprite?
Make sure the "Sprite Mode" in the settings for your images is set to "Single". It was by default "Multiple" for me so that could be the problem.
May I know how to make it work?I follow the video but the health bar never work in the play mode.
I might need abit more info in order to help ! The health bar should change when you press the key that you have assigned for TakeDamage or RestoreHealth.
How would I make it so an enemy attack does damage to the player, instead of pressing B? public class enemyAttack : MonoBehaviour
{
public ParticleSystem ps;
public int damage = -20;
public float TimerForNextAttack, Cooldown;
void Start()
{
}
void Update()
{
if (TimerForNextAttack > 0)
{
TimerForNextAttack -= Time.deltaTime;
}
else if (TimerForNextAttack
Cant get the assets for the health bar, is there another way to make it?
Nevermind I got it
Thanks dude
On my main character, (A Bird) I have attached your HealthBar script., that allows you to press keys to make the bar go Up or Down., I also have a separate player script that controls movement, collisions, etc, etc... also attached to the Bird... Wwithin this second script I have the following which successfully makes the health go down on practically any collision, so it's doing a function contained in Script A (Healthbar) from script B (player controls) - and all works OK..
void OnCollisionEnter2D(Collision2D collision)
{
GetComponent().TakeDamage(2);
StartCoroutine(ResetAfterDelay());
FindObjectOfType().Play("CrateSmash");
}
I want it that if you collide with an apple, it's adds health. I have a script attracted to my apple object, and within it contains the following -:
IEnumerator Die()
{
_hasBeenEaten = true;
ScoreScript.scoreValue += 750;
***This works
GetComponent().sprite = _eatenSprite;
***This works
print("An Apple Has Been Eaten");
***This works
FindObjectOfType().Play("Crunch");
***This works
_particleSystem.Play();
***This works
yield return new WaitForSeconds(1);
***This works
GetComponent().RestoreHealth(25);
This will not restore health
gameObject.SetActive(false);
}
So the second chunk of code is attached to the apple ?? And the first is attached to the bird?
So I believe what is happening is that your trying to "get the component" of BirdHealth on the apple.. however the apple doesn't have a BirdHealth component.. that will be located on your player... So you will need to store the BirdHealth script on a collision.... At the top of the class.. use
private BirdHealth birdHealth;.
And in you OnCollision function use
birdHealth = other.GetComponent();
Then where you want to restore health you can use. birdHealth.RestoreHealth(25);
So your creating a variable and then storing the BirdHealth in the script... Then you have access to all its functions an variables :D
Sorry !!! For 2D. I think its other.gameobject.GetComponent()....
@@NattyGameDev OK Ill give that a go... I did previously create a copy of the entire health system and applied to to various objects to no avail, but yeah I'll give that other.xxxx a go.... I also tried GetComponent().TakeDamage(20); in other scripts and it didn't work. The GetComponent().TakeDamage(20); is only working in my other script because the health script is attached to the same object
@@PeterJohnson76 that's correct ! If your just using "GetComponent....". It will only look at the scripts on *that* gameobject. ..If you would like you can add me on twitter @Gnats_Reserve and you can send me the scripts there and we will work it out ! :D
so are ther any no copyright stuff for the img
No copyright at all ! I made the image and it is free for you to use however you like :D. Everything I supply in my videos to Thank you for watching !
Thank you!!!
How do i make the current health show in text in the screen?
Hey! thanks for the question :) You can do this by;
-creating a new text object (or textmesh) call it something like "healthText"
-creating a public property for this in your health script...
-drag the text object onto the health script in the inspector.
-in your UpdateHealthUI() method assign healthText.text = health;
or even healthText.text = health + "/" + maxHealth;
Hope this helps!
@@NattyGameDev I can`t drag the "healthText" into the public property, that's why I want to ask which property I need to use I used: public text healthText;
@@gaiusoptus4417 TextMeshUGUI :)
@@NattyGameDev thank you, for the quick answer.
Are you doing the second video ?
Yeah! I will be doing the second one very soon ! I started another series but I will move this one up in the list :) Thanks for watching and commenting !
@@NattyGameDev welcome, it's a great looking health system. What's the best way to add health up or down within my game levels within various functions... I also found when adding the health bar to other levels the script wasent woking, despite it being bonded to my main characters prefab.
@@PeterJohnson76 So in regards to adding health up or down, You will always need a reference to the player prefab to call the function from another script.
You can do this by:
•Raycasting (if an enemy is shooting the player),
•Colliders (for physical impact attacks and Picking up healthpacks.),
•By tagging the player prefab with "Player" and using GameObject.FindObjectWithTag("Player");
Then after you have a reference to the player prefab you can call GetComponent().TakeDamage(10); / .RestoreHealth(10);
and regarding the health system working across scenes, are you moving from one scene to another? or just loading a different level, with the UI elements in that scene?
You can try parent the canvas to the player prefab. and also try using DontDestroyOnLoad on the PlayerHealth script.
Let me know if you have any other questions!
Hope this helps! :)
@@NattyGameDev Thanks, but I'm still having issues accessing PlayerHealth.cs and its functions from other scripts. How can I decrease the health from within any one of my other C# scripts.... I think I need help creating the reference.
@@PeterJohnson76 Sure thing! :) how are you wanting to damage the player, from a distance? up close? or over time? what is the method that you want to use to damage the player?
Am I the only one bothered by how he complicates his usage of Angle Brackets for no reason?
Like just press "{" and then Enter, that's it, Visual Studio will fo the rest
lmao no way I just beat the challenge I had no confidence in myself
The HealthBar works great,
but when my Enemy Damage the Player the HealthBar dont work.
(I don´t no how to fix it because im new in Coding Anyone can help me?)
I had override the Healh Script to but it doesn´t Work.
My override Health-Script:
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Threading;
using UnityEngine.UI;
using UnityEngine;
public class PlayerHealth : MonoBehaviour
{
private float Health;
private float lerpTimer;
public float maxHealth = 100f;
public float chipSpeed = 2f;
public Image frontHealthbar;
public Image backHealthbar;
public GameObject DeathUI;
void Start()
{
Health = maxHealth;
}
void Update()
{
Health = Mathf.Clamp(Health, 0, maxHealth);
UpdateHealthUI();
// if (Input.GetKeyDown(KeyCode.A))
// {
// TakeDamage(Random.Range(5, 10));
// }
// if (Input.GetKeyDown(KeyCode.S))
// {
// RestorHealth(Random.Range(5, 10));
}
public void GameOver()
{
UnityEngine.Debug.Log("uIsdead");
DeathUI.SetActive(true);
Time.timeScale = 0f;
}
public void UpdateHealthUI()
{
Debug.Log(Health);
float fillF = frontHealthbar.fillAmount;
float fillB = backHealthbar.fillAmount;
float hFraction = Health / maxHealth;
if(fillB > hFraction)
{
frontHealthbar.fillAmount = hFraction;
backHealthbar.color = Color.red;
lerpTimer += Time.deltaTime;
float percentComplete = lerpTimer / chipSpeed;
backHealthbar.fillAmount = Mathf.Lerp(fillB, hFraction, percentComplete);
}
if(fillF < hFraction)
{
backHealthbar.color = Color.green;
backHealthbar.fillAmount = hFraction;
lerpTimer += Time.deltaTime;
float percentComplete = lerpTimer / chipSpeed;
percentComplete = percentComplete * percentComplete;
frontHealthbar.fillAmount = Mathf.Lerp(fillF, backHealthbar.fillAmount, percentComplete);
}
}
public void TakeDamage(float damage)
{
Health -= damage;
lerpTimer = 0f;
}
public void RestorHealth(float healAmount)
{
Health += healAmount;
lerpTimer = 0f;
}
}
How does you enemy damage the player??
@@NattyGameDev Thsnks for the FeedBack,
I had a public float whit a Attack Range Damage usw. (when the player in Range) the Enemy attack him whit this Code:" void Attack()
{
FindObjectOfType().maxHealth -= Damage;
if (FindObjectOfType().maxHealth
@FyMa2618 so you don't want to change the maxHealth of the player you will want to change the *health* variable.. changing the max health won't affect the size of health bar (you can change the max health if you are leveling up.. which we will do in the next video)
And also..
using FindObjectOfType is an expensive function to call each time you want to attack. So at the top of the class create a variable to store player health.
"private PlayerHealth playerHealth;".
And in start assign the player once.. using
playerHealth = Gameobject.FindObjectWithTag("Player") GetCompnent();. And make sure that you tag the player.
Then you should have the reference to the player.. and you can change the health value..
Thanks for watching !! And I hope this helps !
Message me if you have any other questions ! :D
@FyMa2618 also ! Just remembered you dont need to hardcode changing the health! So instead just use the public TakeDamage(x) function. And pass in the number that you want to damage the player where the x is .. eg:. TakeDamage(20);....
So with what I said in the last comment the full line would be... playerHealth.TakeDamage(20);
@@NattyGameDev Thank´s you, but i had made all what you rode done but it came a Error called:";".
When you need the Changed Code:
using UnityEngine;
public class EnemyAttack : MonoBehaviour
{
private PlayerHealth playerHealth;
public float Range = 1f;
public Transform AttackPoint;
public LayerMask PlayerLayer;
bool PlayerCheck;
public float Damage = 15f;
public float AttackSpeed = 1f;
float nextTimeToFire = 0f;
void Start()
{
playerHealth = Gameobject.FindObjectWithTag("Player") GetCompnent();
}
void Update()
{
PlayerCheck = Physics.CheckSphere(AttackPoint.position, Range, PlayerLayer);
if (PlayerCheck == true && Time.time >= nextTimeToFire)
{
Attack();
nextTimeToFire = Time.time + 1f / AttackSpeed;
}
}
void Attack()
{
FindObjectOfType().maxHealth -= Damage;
if (FindObjectOfType().maxHealth
How can you chip away diagonally?
Not quite sure I understand what you mean, as in not a straight cut off at the end of the sprite?
@@NattyGameDevYes exactly that. Like the Tekken 7 HP bar.
@@Megalilalol1 So unfortunately this cant be done using the "filled" Image type to do this.. you would need this using a 9 sided sprite, or with a mask that moves across from the right-hand side of the health bar.
@@NattyGameDev yeah I actually thought about the mask from right to left its the only solution I can think of
@@Megalilalol1 I'll have a look at what is possible with a 9 sided sprite, you may be able to do it without worrying about a sprite and the backwards math :P
Спасибо дядь!
great
pls full script
i love the images make free site where any game dev can download them pls
power
i like it so can you make one like this one greeeeeeeeeeeen plsssssssssssssssssssssss
epic
Any reason why you don't include the source code in the description? As an intermediate Unity user I don't need the hand guided tutorial but just need a headstart on the logic and code. I'm going to pause the video and copy the code anyway, so why not just include it?
All of the source code and project files + extras will be available via patreon after I have published my page :)
@@NattyGameDev So you are locking copying and pasting behind a paywall? Don't get me wrong it is great to support creators but why should I pay you to allow me to copy and paste your code that you are already willing to share in a video?
I hope this doesn't come off wrong as I really appreciate content creators and what they provide. However I'm a strong believer in open source .
@@spacedog2980 Absolutely! The Patreon will be more for access to Project files
Eg : 3D Models, Unity Scenes, Animations, Textures, Audio Clips,
So any files related to the tutorial videos + other Patreon exclusive assets.
The tutorials are here to help people learn how to code these gameplay systems, also, give the freedom to create your own game using those systems. It is educational content, and I feel like Copy/Paste is not the best approach to learning. We all need to go through process of encountering bugs and researching how to fix them.
The "paywall" will be for those who want to cross reference with my files (Scene and Scripts), along with other Patreon benefits as well.
I am striving to provide content on a similar caliber to that of SkillShare/Udemy courses, without the need to pay for access to the video content :) This won't be launching for a little bit yet, and won't affect the way in which the tutorials are presented on UA-cam.
Hope this addresses any concerns you have! :)
@@NattyGameDev Awesome. Thanks for clearing that up.
I agree on the copy/paste approach not being the best for learning. It is definitely better to go through the motions so you understand what's going on. In my case I already had an understanding of what needs to be done based on your description at the start of the video. So having access to the code straight away would have saved me some time.
That being said, I enjoyed the video and it is indeed a good tutorial.
I appreciate your response.
Hi Natty,
I need this but with a 3D enemy attacking the FPS Character Controller at close range, and the health bar goes down like 20% with each attack can you make it for me?
lmao he's not here to do your homework
:D
My health bar isn't changing when I press the buttons that I set for it to change, and this:
NullReferenceException: Object reference not set to an instance of an object
PlayerHealth.UpdateHealthUI () (at Assets/Scripts/PlayerHealth.cs:37)
PlayerHealth.Update () (at Assets/Scripts/PlayerHealth.cs:24)
keeps popping up in the debug console.
What can I do to fix it?
I got the same error and solved it by going to the playerUI inspector and in the script there you could add the images again and that fixed it
Absolutely great tutorial. Have been following through since your first fps tutorial and have found very little issues. Especially as I'm a complete beginner. Also I'm following this 3yrs later and still pretty solid. However I have come across an error which I no is an easy fix, just like I said am a complete novice to this and think it's just an updated version of unity I'm using. But in the code for the health bar I'm getting a null reference exception error. Object not set to an instance of an object.
Health bar.UpdateHealthUI. it's at health bar.cs 39.
I'm really sorry I no this is basic but only been learning for a week.
Thank u!!