Player Damage

I am a beginner and use to follow “Brackeys” unity tutorials.

But now i want to damage my player (by 10 ) whenever it touches my enemy.:hushed:
here’s my health bar script i’m using…

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerHealth : MonoBehaviour
{
    public int maxHealth = 100;
    public int currentHealth;
    public HealthBar healthBar;
    public GameObject deathEffect;

    // Use this for initialization
    void Start ()
    {
        currentHealth = maxHealth;
        healthBar.SetMaxHealth (maxHealth);
    }
   
    // Update is called once per frame
    void Update ()
    {
        if (Input.GetKeyDown (KeyCode.LeftControl))
        TakeDamage (5);
        if (Input.GetKeyDown (KeyCode.Space))
            TakeDamage (5);

        if (currentHealth <= 0) {
            Die ();
        }
           
    }

   
    void TakeDamage (int damage)
    {
        currentHealth -= damage;
        healthBar.SetHealth (currentHealth);

        }




    void Die ()
    {
        Instantiate (deathEffect, transform.position, Quaternion.identity);
        Destroy(gameObject);
    }
}

Thank You in advance.:smile::smile:

@SamlicsX

(Please edit your post to use code tags, now it is a green mess that is hard to read… )

Maybe you should read some C# basics tutorials instead?

I’m not quite sure what the question is either, or what the problem is you have… but some ideas:

You already have a method that can take any integer amount for damage.

To check if you collided with enemy you can use OnTriggerEnter2D or OnCollisionEnter2D.

1 Like

Sorry but i am trying to do so and it didn’t work.

So can you please tell me what to do.

You reply will be appreciated

If you set a tag for the enemy in the inspector to enemy, then create an OnCollisionEnter2D method (make sure your enemy has some kind of 2d collider like a boxcollider2d attached to it), then you can say something like if the collision.gameObject.tag.Equals(“enemy”) then takedamage(10)

1 Like