UI Healthbar problem

Hi, im very new to coding and unity. Im trying to make a little survival game and . So my current problem is, I have 2 Bars. A health and a Hunger bar. if the Hugner bar is 0 the Health bar should lose value. That what it does BUT my image that I use in the UI dont update the fill of the image itself.

This is my script for the players Health

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class PlayerHealthbar : MonoBehaviour
{
    public Image Bar;
    public float max_health = 100f;
    public float cur_health = 0f;
    

	// Use this for initialization
	void Start ()
    {
        cur_health = max_health;
	}

    public void decreaseHealth() 
    {
        cur_health -= 10f;
    }

    void SetHealth(float myhealth)
    {
        Bar.fillAmount = myhealth;
        float calc_health = cur_health / max_health;
        SetHealth(calc_health);
    }
	// Update is called once per frame
	void Update ()
    {
       

       



            	
	}
}

And this is my script for the players Hunger

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

[RequireComponent(typeof(PlayerHealthbar))]
public class PlayerHunger : MonoBehaviour
{
    public Image Bar;
    public float max_hunger = 100f;
    public float cur_hunger = 0f;


    // Use this for initialization
    void Start()
    {
        cur_hunger = max_hunger;
        InvokeRepeating("decreaseHunger", 0f, 10f);
    }

    void decreaseHunger()
    {
        cur_hunger -= 1f;
        if (cur_hunger <= 0)
        {
            cur_hunger = 0;
            GetComponent<PlayerHealthbar>().decreaseHealth();
        }
        float calc_hunger = cur_hunger / max_hunger;
        SetHunger(calc_hunger);
    }
    void SetHunger(float myhunger)
    {
        Bar.fillAmount = myhunger;
        
    }
    // Update is called once per frame
    void Update()
    {

    }
}

Im really knew to scripting and I wrote this by change some scripts that I saw in tutorials

Something that hit me is that from your “DecreaseHealth” method never call SetHealth which appear to be setting your hp image fillrate, also in SetHealth you call SetHealth() again, so calling that method will get you stuck in an endless loop and probably cause a stack overflow exception. it make more sense the way you’ve written in your hunger class. :slight_smile:

public void decreaseHealth() {
        cur_health -= 10f;
        float calc = cur_health / max_health;
        SetHealth( calc );
}

    void SetHealth(float myhealth) {
        Bar.fillAmount = myhealth;
}
2 Likes

Thank You so much. Im really trying to get in this, hopefully lateron I will see things like dat earlier :slight_smile:

You’re welcome. :slight_smile:
Just as with everything else it takes time, practice and alot of trying to learn coding but just keep it up and be patient and you will get there! :slight_smile: