How do I make my Gun do damage

Hi,

I have been trying to figure out why my bullet doesn’t do any damage to my player health bar

Player.cs

public class Player : MonoBehaviour
{
    public int maxHealth = 100;
    public int currenthealth;
    public Healthbar healthbar;

    void OnCollisionEnter(Collision collision)
    {
        if (collision.collider.gameObject.tag == "Bullet")
        {
            TakeDamage(20);
        }
    }

    public void TakeDamage(int damage)
    {
        currenthealth -= damage;
        healthbar.SetHealthBar(currenthealth);
    }
}

Healthbar.cs

public class Healthbar : MonoBehaviour
{
    public Slider slider;
    public Gradient gradient;
    public Image fill;
    public void SetMaxHealth(int health)
    {
        slider.maxValue = health;
        slider.value = health;
        fill.color = gradient.Evaluate(1f);
    }

    public void SetHealthBar(int health)
    {
        slider.value = health;

        fill.color = gradient.Evaluate(slider.normalizedValue);
    }
}

Hi,

I don’t know if you shared the entire Player.cs script but there is no place where you set your currentHealth variable to the maxHealth variable value.

You can do it in the void Start() method of your Player.cs script.

i have tried adding it in it still doesn’t work
here is the script for player

void Start()
{
    currenthealth = maxHealth;
    healthbar.SetMaxHealth(maxHealth);
}

void OnCollisionEnter(Collision collision)
{
    if (collision.collider.gameObject.tag == "Bullet")
    {
        TakeDamage(20);
    }
}

public void TakeDamage(int damage)
{
    currenthealth -= damage;
    healthbar.SetHealthBar(currenthealth);
}

Hi Ricky,
to get to the root of this problem, you should check if every functionality is working as intended.

Add this line:

Debug.LogWarning("(FUNCTION NAME HERE) is working as intended.");

Then, test it and look for any missing warnings.

In this case it could be the slider being limited to values 0 and 1?
Is it limited to only int (as it should be)?
Is a collider missing?
Is the bullet collider checked as is trigger? (If you want no knockback you should use this and OnTriggerEnter(), if I am not mistaken)