How to make a Better Health Bar in Unity : Chip Away Tutorial

Поділитися
Вставка
  • Опубліковано 25 лис 2024

КОМЕНТАРІ • 191

  • @Massive-3D
    @Massive-3D 2 роки тому +32

    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

  • @dallas8598
    @dallas8598 Рік тому

    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!

  • @Stratoscaster
    @Stratoscaster 10 місяців тому +1

    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.

  • @ashishbhogasamudram233
    @ashishbhogasamudram233 Рік тому +6

    I've never found a series that has helped me so much in Unity. Keep up the good work!

  • @Biplaneado
    @Biplaneado Рік тому +4

    This is one of the best explanations regarding healthbars in unity imo. Good videos man, thanks!

  • @Thouova
    @Thouova Рік тому +8

    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.

  • @homemadeswtor
    @homemadeswtor 8 місяців тому

    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

  • @ginoantenucci6424
    @ginoantenucci6424 2 роки тому +1

    I have seen so many tutorials but this one Is so good This channel is so so so underrated

  • @tagscientist
    @tagscientist 3 роки тому +10

    Excellent video - your presentation is very clear and easy to follow. Thanks

  • @Denkata7622
    @Denkata7622 7 місяців тому

    The best tutorial ever! I wonder why you still haven't reached 1 mil.

  • @verbatim7488
    @verbatim7488 2 роки тому +3

    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

  • @JakeMakesGames
    @JakeMakesGames 2 роки тому +2

    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!

  • @steeltm521
    @steeltm521 3 роки тому +3

    Thank you for the tutorial! It is very helpful.

  • @codinginflow
    @codinginflow 3 роки тому

    Looks really cool

  • @valzzu
    @valzzu 3 роки тому +2

    Thank you! Exactly what I was looking for. You earned new subscriber :)

  • @roeegaming3528
    @roeegaming3528 Місяць тому

    everything works great!, but when I'm adding heals I dont see the green color going up, just the normal health bar

  • @michaeltrout6847
    @michaeltrout6847 Рік тому +1

    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!

    • @torbenkramm2725
      @torbenkramm2725 Рік тому

      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?

    • @NewYorkNixDa
      @NewYorkNixDa Рік тому +2

      @@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.)

  • @moonliteclipsegaming
    @moonliteclipsegaming Рік тому

    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

  • @orvobx7909
    @orvobx7909 2 роки тому

    dude your videos are so great. thank you so much

  • @duztine
    @duztine 2 роки тому

    Very useful... thank you and i look forward to your great videos

  • @JollyDMoss9297
    @JollyDMoss9297 Рік тому +1

    took me way more time that it should have , as much i expected , im making progress i guess, code looks less scary.

  • @asdd2a
    @asdd2a 2 роки тому +2

    isn't that lerp timer variable keep adding?

    • @lilvan1018
      @lilvan1018 Рік тому

      Yes, but i think its okay, thats how Update() doing anyway, called every frame

  • @Josh3DMorris
    @Josh3DMorris 4 роки тому

    Really helpful, would recommend 10/10

  • @madcowboy5700
    @madcowboy5700 3 роки тому +3

    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

    • @NattyGameDev
      @NattyGameDev  3 роки тому +8

      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 !! :)

    • @Tooni8282
      @Tooni8282 3 роки тому

      @@NattyGameDev great stuff, thanks for this

    • @nkxk26
      @nkxk26 Рік тому

      @@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.

    • @NewYorkNixDa
      @NewYorkNixDa Рік тому

      @@nkxk26 maybe set it to 0f same as lerpTimer ;-)

  • @Ranting4Rent
    @Ranting4Rent 2 місяці тому

    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?

  • @grenadier1783
    @grenadier1783 2 роки тому +3

    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)"

    • @krzaczastyyt6547
      @krzaczastyyt6547 3 місяці тому

      its becouse you are using the new unity input system and he is using the legacy one (the old one).

  • @dayxgamerzop
    @dayxgamerzop 4 місяці тому

    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

  • @thatonedude8209
    @thatonedude8209 2 роки тому +1

    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

    • @godpowernwachukwu
      @godpowernwachukwu Рік тому +1

      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.

  • @2MARR8
    @2MARR8 3 роки тому

    This helped me immensely, thank you!

    • @NattyGameDev
      @NattyGameDev  3 роки тому +1

      I am super happy this helped! Thank you for watching :)

  • @sonermuratduhan5687
    @sonermuratduhan5687 3 роки тому

    Thank You for great tutorial
    keep up the good work

  • @ahakanyildiz
    @ahakanyildiz 3 роки тому +1

    Nicely done.

  • @Sproute-RL
    @Sproute-RL 8 місяців тому +1

    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;
    }
    }

  • @AlexJavier.93
    @AlexJavier.93 3 роки тому +1

    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.

    • @NattyGameDev
      @NattyGameDev  3 роки тому

      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!

  • @GreenGnoblin
    @GreenGnoblin 3 роки тому

    Very nice video! You got a new subscriber. Keep up the good work!

    • @NattyGameDev
      @NattyGameDev  3 роки тому +1

      Thanks so much !

    • @GreenGnoblin
      @GreenGnoblin 3 роки тому +2

      @@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.

    • @NattyGameDev
      @NattyGameDev  3 роки тому +1

      @@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 ! :)

    • @GreenGnoblin
      @GreenGnoblin 3 роки тому

      @@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.

  • @SekyoT
    @SekyoT 2 роки тому

    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

  • @ParagonJeck
    @ParagonJeck 2 роки тому

    Thanks. Everything is work and stylish)

  • @mystocity
    @mystocity Рік тому

    couldn't find the requested platform texture settings help

  • @el_yagym
    @el_yagym 2 роки тому

    This is excellent! Thank you so much! New suscriber! of course!

  • @JollyDMoss9297
    @JollyDMoss9297 Рік тому

    just a question , what should i do to stop number increasing in console , right

  • @orvobx7909
    @orvobx7909 2 роки тому

    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

  • @qwyit
    @qwyit Рік тому

    Where is the image type dropdown I don't see it

  • @kujo48
    @kujo48 Рік тому

    Can you start adding a link so you can copy and past all the code

  • @RockSoldier86
    @RockSoldier86 2 роки тому

    yo, nice health bar and thanks for recommendation))

  • @imjess3959
    @imjess3959 3 роки тому

    Thanks, you saved me

  • @luckyowl859
    @luckyowl859 Рік тому

    why when i imported my images they are faded

  • @stunUnity
    @stunUnity 2 роки тому

    Thank for your helpful tip

  • @martinjuda5236
    @martinjuda5236 Рік тому

    S+ tier tutorial

  • @minhquanhuynh8763
    @minhquanhuynh8763 3 роки тому

    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

    • @NattyGameDev
      @NattyGameDev  3 роки тому +1

      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!

  • @orvobx7909
    @orvobx7909 2 роки тому

    how did you add the frame onto the panel as the background? It wont let me drag and drop anything onto it

    • @orvobx7909
      @orvobx7909 2 роки тому

      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"

  • @SynchronousGamingSGYT
    @SynchronousGamingSGYT 15 днів тому

    restore health not working bro

  • @张烨尘
    @张烨尘 8 місяців тому

    Where can i get the heartIcon?

  • @jordanfernandes4409
    @jordanfernandes4409 3 роки тому

    Just what I wanted....thanks

  • @lilvan1018
    @lilvan1018 Рік тому

    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

    • @tiktakt0025
      @tiktakt0025 Рік тому

      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

  • @RealsomegamerYT9000
    @RealsomegamerYT9000 Рік тому +1

    can anyone drop the code?

  • @RealsomegamerYT9000
    @RealsomegamerYT9000 Рік тому +1

    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;
    }
    }

    • @RyanLovell-l1y
      @RyanLovell-l1y День тому

      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)

  • @danforyou
    @danforyou 4 місяці тому

    I can't drag and drop a frame onto the source image in the panel
    How do I fix it?

    • @ttvBeansFN
      @ttvBeansFN 3 місяці тому

      Have you made the frame a sprite?

    • @CB66941
      @CB66941 14 днів тому

      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.

  • @Radeux-l2e
    @Radeux-l2e 3 роки тому

    May I know how to make it work?I follow the video but the health bar never work in the play mode.

    • @NattyGameDev
      @NattyGameDev  3 роки тому

      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.

  • @robro498
    @robro498 2 роки тому

    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

  • @gumball5372
    @gumball5372 5 місяців тому

    Cant get the assets for the health bar, is there another way to make it?

  • @샤샤샤-e9c
    @샤샤샤-e9c Рік тому

    Thanks dude

  • @PeterJohnson76
    @PeterJohnson76 3 роки тому +1

    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);
    }

    • @NattyGameDev
      @NattyGameDev  3 роки тому

      So the second chunk of code is attached to the apple ?? And the first is attached to the bird?

    • @NattyGameDev
      @NattyGameDev  3 роки тому

      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
      @NattyGameDev  3 роки тому

      Sorry !!! For 2D. I think its other.gameobject.GetComponent()....

    • @PeterJohnson76
      @PeterJohnson76 3 роки тому

      @@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

    • @NattyGameDev
      @NattyGameDev  3 роки тому +1

      @@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

  • @samuelgirmagirma4019
    @samuelgirmagirma4019 3 роки тому

    so are ther any no copyright stuff for the img

    • @NattyGameDev
      @NattyGameDev  3 роки тому +1

      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 !

  • @calvinms7503
    @calvinms7503 2 роки тому

    Thank you!!!

  • @imjess3959
    @imjess3959 3 роки тому

    How do i make the current health show in text in the screen?

    • @NattyGameDev
      @NattyGameDev  3 роки тому +1

      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!

    • @gaiusoptus4417
      @gaiusoptus4417 2 роки тому

      @@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;

    • @NattyGameDev
      @NattyGameDev  2 роки тому

      @@gaiusoptus4417 TextMeshUGUI :)

    • @gaiusoptus4417
      @gaiusoptus4417 2 роки тому

      @@NattyGameDev thank you, for the quick answer.

  • @PeterJohnson76
    @PeterJohnson76 3 роки тому

    Are you doing the second video ?

    • @NattyGameDev
      @NattyGameDev  3 роки тому +1

      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 !

    • @PeterJohnson76
      @PeterJohnson76 3 роки тому

      @@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.

    • @NattyGameDev
      @NattyGameDev  3 роки тому +1

      @@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! :)

    • @PeterJohnson76
      @PeterJohnson76 3 роки тому

      @@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.

    • @NattyGameDev
      @NattyGameDev  3 роки тому

      @@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?

  • @sunbleachedangel
    @sunbleachedangel Рік тому

    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

  • @inquisitive240
    @inquisitive240 Рік тому +1

    lmao no way I just beat the challenge I had no confidence in myself

  • @DieserDeutscheTyp
    @DieserDeutscheTyp 3 роки тому +1

    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
      @NattyGameDev  3 роки тому +1

      How does you enemy damage the player??

    • @DieserDeutscheTyp
      @DieserDeutscheTyp 3 роки тому

      @@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

    • @NattyGameDev
      @NattyGameDev  3 роки тому +2

      @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

    • @NattyGameDev
      @NattyGameDev  3 роки тому +1

      @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);

    • @DieserDeutscheTyp
      @DieserDeutscheTyp 3 роки тому

      ​@@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
    @Megalilalol1 3 роки тому

    How can you chip away diagonally?

    • @NattyGameDev
      @NattyGameDev  3 роки тому

      Not quite sure I understand what you mean, as in not a straight cut off at the end of the sprite?

    • @Megalilalol1
      @Megalilalol1 3 роки тому

      @@NattyGameDevYes exactly that. Like the Tekken 7 HP bar.

    • @NattyGameDev
      @NattyGameDev  3 роки тому

      @@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
      @Megalilalol1 3 роки тому

      @@NattyGameDev yeah I actually thought about the mask from right to left its the only solution I can think of

    • @NattyGameDev
      @NattyGameDev  3 роки тому

      @@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

  • @Pa3BeDka_Gaming
    @Pa3BeDka_Gaming 2 роки тому +1

    Спасибо дядь!

  • @ReddLolz
    @ReddLolz 4 роки тому

    great

  • @ItzDeadPoolBlox
    @ItzDeadPoolBlox Рік тому

    pls full script

  • @samuelgirmagirma4019
    @samuelgirmagirma4019 3 роки тому +1

    i love the images make free site where any game dev can download them pls

  • @samuelgirmagirma4019
    @samuelgirmagirma4019 3 роки тому

    i like it so can you make one like this one greeeeeeeeeeeen plsssssssssssssssssssssss

  • @-Bill-Clinton-
    @-Bill-Clinton- Рік тому

    epic

  • @spacedog2980
    @spacedog2980 2 роки тому

    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
      @NattyGameDev  2 роки тому

      All of the source code and project files + extras will be available via patreon after I have published my page :)

    • @spacedog2980
      @spacedog2980 2 роки тому

      @@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 .

    • @NattyGameDev
      @NattyGameDev  2 роки тому +1

      ​@@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! :)

    • @spacedog2980
      @spacedog2980 2 роки тому

      @@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.

  • @Stinger-rq4gy
    @Stinger-rq4gy 3 роки тому

    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?

    • @spacedog2980
      @spacedog2980 2 роки тому +3

      lmao he's not here to do your homework

  • @yahoova994
    @yahoova994 2 роки тому

    :D

  • @U.S.Postal
    @U.S.Postal 5 місяців тому

    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?

    • @luddz1488
      @luddz1488 2 місяці тому

      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

  • @gagaelite7115
    @gagaelite7115 10 місяців тому

    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.

  • @levanas_
    @levanas_ Рік тому

    Thank u!!