How to make player lose health when touch an enemy?

hello i am making a 2d game and i made a health script for my game. i do not know how to code and i followed brackeyes tutorial. I just want replace the “if touch space then loose health” to something like “if touch collider2d with tag (tag) then loose health”. Code for the health here :

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

public class Health : MonoBehaviour
{

public Slider slider;

public float currentHealth;

void Start()
{
slider.value = currentHealth;
slider.maxValue = currentHealth;
}
void Update()
{
if (Input.GetKey(KeyCode.Space))
{
TakeDamage(1);
}
}

void TakeDamage(int damage)
{
slider.value -= damage;
}
}

thank you and goodbye

also how to like make an animation when the health goes to 0, and when the animation is finish : restart the game

Please use code tags: Using code tags properly

How to report problems productively in the Unity3D forums:

http://plbm.com/?p=220

Help us to help you.

thanks!

btw what is the pause key name on the xbox one controller?

Plug one in, iterate all the InputManager’s keys, display them, and see which one moves.

That’s all I would do. If you read on the net that it is “XYZ” and you code up that and it doesn’t work, you’re going to go back to the above in any case. Just do it now, save a lot of time.

1 Like

use this:

or this:

make sure the stuff your triggering has a rigid-body and whether or not it moves use kinematic and set colliders to trigger (or not depends on what is happening).

   void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.tag == "Enemy")
        {
            //collision.gameObject.SendMessage("ApplyDamage", 10);
            TakeDamage(1);
        }
    }

The other gameObject needs the tag “Enemy” to work.
The part i comment out you can use if the enemy should take the damage and he has a ApplyDamage method.

Hi thanks
What parameter should I enter in “collision” when I call the function?

You do not call that function.

The physics system inside of Unity will call that function for you.

Unity will only call that when you meet ALL the conditions for it, as outlined in the documentation.

When it calls, that collision will contain all the information you need about the collision that just happened.

Maybe this could also help you.

Thanks! I’ll try A.S.A.P

Hi, I am creating a top down game, i used the same code and is working perfectly fine, the problems come when, I hit an enemy, I take one damage, but then, if I stay steel, I will not suffer more damage, I was trying to give invulnerabilities frames or knockback, but couldnt find any code, can someone help please.

You may be using OnCollisionEnter() or OnTriggerEnter().
Use the function OnCollisionStay() or OnTriggerStay()