Good day everyone! I’m still relatively new to Unity and I’m working on a 3D RPG game by following Brackey’s tutorial on Youtube.
I’d like to implement a health potion that will increase the player’s health, however I’ve ran into a bit of a problem. When I use the potion from my inventory it doesn’t do anything.
Here’s my HealthPotion script that derives from my Item script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "HealthPotion", menuName = "Inventory/Potion")]
public class HealthPotion : Item
{
public int health;
public GameObject player;
public override void Use()
{
base.Use();
player.GetComponent<CharacterStats>().currentHealth += health;
Debug.Log("Increasing health by " + health);
}
}
Item script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Item", menuName = "Inventory/Item")]
public class Item : ScriptableObject
{
new public string name = "New Item"; // name of the item
public Sprite icon = null; // item icon
public bool isDefaultItem = false; // is the item default wear
public virtual void Use()
{
// Use the item
// Something might happen
Debug.Log("Using " + name);
}
// removes the item from inventory when it's equipped
public void RemoveFromInventory()
{
Inventory.instance.Remove(this);
}
}
CharacterStats script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterStats : MonoBehaviour
{
public int maxHealth = 100; // default max health;
public int currentHealth; // current health
public Stat damage; // damage value
public Stat armor; // armor value
void Awake()
{
currentHealth = maxHealth;
}
void Update ()
{
if (Input.GetKeyDown(KeyCode.T))
{
TakeDamage(10);
}
}
public void TakeDamage(int damage)
{
damage -= armor.GetValue();
damage = Mathf.Clamp(damage, 0, int.MaxValue); // so that the damage never goes below 0
currentHealth -= damage; // decreasing health of character whenever they take damage
Debug.Log(transform.name + " takes " + damage + " damage");
// if health is below 0, the player or the enemy will die
if (currentHealth <= 0)
{
Die();
}
}
public virtual void Die()
{
// Die in some way
// This method is meant to be overwritten
Debug.Log(transform.name + " died");
}
}
When I use the potion, it successfully outputs the Debug.Log statement in the HealthPotion script however it doesn’t actually apply the change to my current health. Where am I going wrong?