Forum begins after the advertisement:

 


[Part 11] Health pickup won’t refill HP

Home Forums Video Game Tutorial Series Creating a Rogue-like Shoot-em Up in Unity [Part 11] Health pickup won’t refill HP

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #18607
    Bruno Azalim
    Level 3
    Participant
    Helpful?
    Up
    1
    ::

    Hi! i’ve been following the series so far without any problems but now in the end of part 11 i’ve realized that the health pickups are not filling my HP. i’ve checked in the debug mode and saw that its really not updating the currentHP (not only the healthbar display). Can anyone help me on this ?

    The magnet effect is also not working but i saw it was not working on the video so i guess its going to be fixed on part 17

    these are my scripts:

    PlayerStats:

    using NUnit.Framework;
    using System.Collections.Generic;
    using TMPro;
    using UnityEngine;
    using UnityEngine.UI;
    
    public class PlayerStats : MonoBehaviour
    {
        CharacterSO characterData;
    
        //Current stats
        float currentHealth;
        float currentRecovery;
        float currentMoveSpeed;
        float currentMight;
        float currentProjectileSpeed;
        float currentMagnet;
    
        #region Current Stats Properties
        public float CurrentHealth
        {
            get { return currentHealth; } 
            set
            {
                //check if the value has changed
                if(currentHealth != value)
                {
                    currentHealth = value;
                    if(GameManager.instance != null)
                    {
                        GameManager.instance.currentHealthDisplay.text = "Health: " + currentHealth;
                    }
                    //add any aditional logic here that need to be executed when the value changes
                }
            }
        }
    
        public float CurrentRecovery
        {
            get { return currentRecovery; }
            set
            {
                //check if the value has changed
                if (currentRecovery != value)
                {
                    currentRecovery = value;
                    if (GameManager.instance != null)
                    {
                        GameManager.instance.currentRecoveryDisplay.text = "Recovery: " + currentRecovery;
                    }
                    //add any aditional logic here that need to be executed when the value changes
                }
            }
        }
    
        public float CurrentMoveSpeed
        {
            get { return currentMoveSpeed; }
            set
            {
                //check if the value has changed
                if (currentMoveSpeed != value)
                {
                    currentMoveSpeed = value;
                    if (GameManager.instance != null)
                    {
                        GameManager.instance.currentMoveSpeedDisplay.text = "Move Speed: " + currentMoveSpeed;
                    }
                    //add any aditional logic here that need to be executed when the value changes
                }
            }
        }
    
        public float CurrentMight
        {
            get { return currentMight; }
            set
            {
                //check if the value has changed
                if (currentMight != value)
                {
                    currentMight = value;
                    if (GameManager.instance != null)
                    {
                        GameManager.instance.currentMightDisplay.text = "Might: " + currentMight;
                    }
                    //add any aditional logic here that need to be executed when the value changes
                }
            }
        }
    
        public float CurrentProjectileSpeed
        {
            get { return currentProjectileSpeed; }
            set
            {
                //check if the value has changed
                if (currentProjectileSpeed != value)
                {
                    currentProjectileSpeed = value;
                    if (GameManager.instance != null)
                    {
                        GameManager.instance.currentProjectileSpeedDisplay.text = "Projectile Speed: " + currentProjectileSpeed;
                    }
                    //add any aditional logic here that need to be executed when the value changes
                }
            }
        }
    
        public float CurrentMagnet
        {
            get { return currentMagnet; }
            set
            {
                //check if the value has changed
                if (currentMagnet != value)
                {
                    currentMagnet = value;
                    if (GameManager.instance != null)
                    {
                        GameManager.instance.currentMagnetDisplay.text = "Magnet: " + currentMagnet;
                    }
                    //add any aditional logic here that need to be executed when the value changes
                }
            }
        }
        #endregion
    
        //Experience and level of the player
        [Header("Experience/Level")]
        public int experience = 0;
        public int level = 1;
        public int experienceCap;
    
    
        //define a level range and the corresponding experience cap increase for that range
        [System.Serializable]
        public class LevelRange
        {
            public int startLevel;
            public int endLevel;
            public int experienceCapIncrease;
        }
    
        //i-Frames
        [Header("I-Frames")]
        public float invincibilityDuration;
        float invincibilityTimer;
        bool isInvincible;
    
        public List<LevelRange> levelRanges;
    
        InventoryManager inventory;
        public int weaponIndex;
        public int passiveItemIndex;
    
        [Header("UI")]
        public Image healthBar;
        public Image expBar;
        public TextMeshProUGUI levelText;
    
    
        public GameObject secondWeaponTest;
        public GameObject firstPassiveItemTest, secondPassiveItemTest;
    
        void Awake()
        {
            characterData = CharacterSelector.GetData();
            CharacterSelector.instance.DestroySingleton();
    
            inventory = GetComponent<InventoryManager>();
    
            //Assign the variables
            CurrentHealth = characterData.MaxHealth;
            CurrentRecovery = characterData.Recovery;
            CurrentMoveSpeed = characterData.MoveSpeed;
            CurrentMight = characterData.Might;
            CurrentProjectileSpeed = characterData.ProjectileSpeed;
            CurrentMagnet = characterData.Magnet;
    
            //spawn the starting weapon
            SpawnWeapon(characterData.StartingWeapon);
            //SpawnWeapon(secondWeaponTest);
            //SpawnPassiveItem(firstPassiveItemTest);
            SpawnPassiveItem(secondPassiveItemTest);
    
        }
    
        void Start()
        {
            //initialize the experience cap as the first experience cap increase
            experienceCap = levelRanges[0].experienceCapIncrease;
    
            //set the current stats display
            GameManager.instance.currentHealthDisplay.text = "Health: " + currentHealth;
            GameManager.instance.currentRecoveryDisplay.text = "Recovery: " + currentRecovery;
            GameManager.instance.currentMoveSpeedDisplay.text = "Move Speed: " + currentMoveSpeed;
            GameManager.instance.currentMightDisplay.text = "Might: " + currentMight;
            GameManager.instance.currentProjectileSpeedDisplay.text = "Projectile Speed: " + currentProjectileSpeed;
            GameManager.instance.currentMagnetDisplay.text = "Magnet: " + currentMagnet;
    
            GameManager.instance.AssignChosenCharacterUI(characterData);
    
            UpdateHealthBar();
            UpdateExpBar();
            UpdateLevelText();
        }
    
        private void Update()
        {
            if(invincibilityTimer > 0)
            {
                invincibilityTimer -= Time.deltaTime;
            }
            else if (isInvincible)
            {
                isInvincible = false;
            }
    
            Recover();
        }
    
        public void IncreaseExperience(int amount)
        {
            experience += amount;
    
            LevelUpChecker();
    
            UpdateExpBar();
        }
    
        void LevelUpChecker()
        {
            if(experience >= experienceCap)
            {
                level ++;
                experience -= experienceCap;
    
                int experienceCapIncrease = 0;
                foreach(LevelRange range in levelRanges)
                {
                    if(level >= range.startLevel && level <= range.endLevel)
                    {
                        experienceCapIncrease = range.experienceCapIncrease;
                        break;
                    }
                }
                experienceCap += experienceCapIncrease;
    
                UpdateLevelText();
    
                GameManager.instance.StartLevelUp();
            }
        }
    
        void UpdateExpBar()
        {
            expBar.fillAmount = (float)experience / experienceCap;
        }
    
        void UpdateLevelText()
        {
            levelText.text = "Level " + level.ToString();
        }
    
        public void TakeDamage(float dmg)
        {
            //if the player is not currently invincible, reduce health and start invincibility
            if(!isInvincible)
            {
                CurrentHealth -= dmg;
    
                invincibilityTimer = invincibilityDuration;
                isInvincible = true;
    
                if (CurrentHealth <= 0)
                {
                    Kill();
                }
    
                UpdateHealthBar();
            }
    
        }
    
        void UpdateHealthBar()
        {
            //Update health bar
            healthBar.fillAmount = currentHealth / characterData.MaxHealth;
        }
    
        public void Kill()
        {
            if(!GameManager.instance.isGameOver)
            {
                GameManager.instance.AssignLevelReachedUI(level);
                GameManager.instance.AssignChosenWeaponsAndPassiveItemsUI(inventory.weaponUISlots, inventory.passiveItemUISlots);
                GameManager.instance.GameOver();
            }
        }
    
        public void RestoreHealth(float amount)
        {
            if(CurrentHealth < characterData.MaxHealth)
            {
                CurrentHealth += amount;
    
                //Make sure the player's health doesnt exceed their maximum health
                if (CurrentHealth > characterData.MaxHealth)
                {
                    CurrentHealth = characterData.MaxHealth;
                }
            }
    
        }
    
        void Recover()
        {
            if(CurrentHealth < characterData.MaxHealth)
            {
                CurrentHealth += CurrentRecovery * Time.deltaTime;
    
                //Make sure the player's health doesnt exceed their maximum health
                if(CurrentHealth > characterData.MaxHealth)
                {
                    CurrentHealth = characterData.MaxHealth;
                }
            }
        }
    
        public void SpawnWeapon(GameObject weapon)
        {
            //checking if the slots are full and returning if it is
            if(weaponIndex >= inventory.weaponSlots.Count - 1) //must be -1 cause the list starts from 0
            {
                Debug.LogError("Inventory slots already full");
                return;
            }
    
            //spawn the starting weapon
            GameObject spawnedWeapon = Instantiate(weapon, transform.position, Quaternion.identity);
            spawnedWeapon.transform.SetParent(transform); //set weapon to be a child of the player
            inventory.AddWeapon(weaponIndex, spawnedWeapon.GetComponent<WeaponController>()); //add the weapon to its inventory slot
    
            weaponIndex++;
        }
    
        public void SpawnPassiveItem(GameObject passiveItem)
        {
            //checking if the slots are full and returning if it is
            if (passiveItemIndex >= inventory.passiveItemSlots.Count - 1) //must be -1 cause the list starts from 0
            {
                Debug.LogError("Inventory slots already full");
                return;
            }
    
            //spawn the starting passive item
            GameObject spawnedPassiveItem = Instantiate(passiveItem, transform.position, Quaternion.identity);
            spawnedPassiveItem.transform.SetParent(transform); //set weapon to be a child of the player
            inventory.AddPassiveItem(passiveItemIndex, spawnedPassiveItem.GetComponent<PassiveItem>()); //add the weapon to its inventory slot
    
            passiveItemIndex++;
        }
    
    }
    

    Pickup

    using UnityEngine;
    
    public class Pickup : MonoBehaviour, iCollectible
    {
        protected bool hasBeenCollected = false;
    
        public virtual void Collect()
        {
            hasBeenCollected = true;
        }
    
        private void OnTriggerEnter2D(Collider2D collision)
        {
            if (collision.CompareTag("Player"))
            {
                Destroy(gameObject);
            }
    
        }
    }
    

    LifeCrystal (the name of my hp pickup)

    using UnityEngine;
    
    public class LifeCrystal : Pickup
    {
        public float healthToRestore;
    
        public override void Collect()
        {
            if(hasBeenCollected)
            {
                return;
            }
            else
            {
                base.Collect();
            }
    
            PlayerStats player = FindFirstObjectByType<PlayerStats>();
            player.RestoreHealth(healthToRestore);
    
    
        }
    
    
    }
    
    has upvoted this post.
    #18608
    Alp Apustaja
    Level 9
    AI Assistant
    (BETA)
    Helpful?
    Up
    1
    ::

    Based on the reference information, the solution is to call UpdateHealthBar() in the RestoreHealth() method of the PlayerStats script. This will ensure that the health bar updates immediately after restoring health.

    Modify the RestoreHealth() method in PlayerStats to look like this:

    public void RestoreHealth(float amount)
    {
        if(CurrentHealth  characterData.MaxHealth)
            {
                CurrentHealth = characterData.MaxHealth;
            }
    
            UpdateHealthBar(); // Add this line
        }
    }

    This change will update the health bar whenever health is restored, fixing the issue of the health bar not updating after picking up a health pickup.

    has upvoted this post.
    #18609
    Bruno Azalim
    Level 3
    Participant
    Helpful?
    Up
    1
    ::

    this has solved my problem, thank you AI!

    has upvoted this post.
    #18610
    Alp Apustaja
    Level 9
    AI Assistant
    (BETA)
    Helpful?
    Up
    0
    ::

    You’re welcome! I’m glad I could help you solve the health pickup issue in your Vampire Survivors-style game.

Viewing 4 posts - 1 through 4 (of 4 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: