Why my HurtPlayer script damages only once?

Hi guys,

I wonder why damage only occurs once, I’d like it to keep damaging, but I don’t know why. My healthmanager is working as inteded. Here is what happens: my 2d player keeps walking until he reaches an enemy, that’s when the damage occurs, but only once.

Here is my HurtPlayer script:

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

public class HurtPlayer : MonoBehaviour {

public int damageToGive;

// Use this for initialization
void Start () {
	
}

// Update is called once per frame
void Update () {
	
}

void OnCollisionEnter2D(Collision2D other)
{
	if (other.gameObject.name == "Player") 
	{
		other.gameObject.GetComponent<PlayerHealthManager> ().HurtPlayer (damageToGive);
	}
}

}"

Regards.

As I do not know anything else other than the script I am going to assume that whatever runs the script is probably only able to run it once. Like a onClick function.

It also maybe because there is more than one GameObject that is named Player or very similar in names.

But this is just assumption.

Hello @crawler167, you can put an IEnumerator ! Like StartCoroutine(DamagePlayer()) and create tags for your player and your enemy ! There’s one thing : do you want to collide or trigger ? If you collide, a coroutine might be useful ! If you want to Trigger, a coroutine is’nt needed !

I give you 2 scripts like yours :

1ST Script

     public int damageToGive;
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     void Update () {
         
     }
     void OnTriggerEnter2D(Collider2D other)
     {
         if (other.gameObject.tag == "Player") 
         {
             other.gameObject.GetComponent<PlayerHealthManager> ().HurtPlayer (damageToGive);
         }
     }

2ND Script

     public int damageToGive;
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     void Update () {
         
     }
     void OnCollisionEnter2D(Collision2D other)
     {
         if (other.gameObject.tag == "Player") 
         {
             StartCoroutine(PlayerDamage());
         }
     }

    void OnCollisionExit2D(Collision2D other2)
    {
        if (other2.gameObject.tag == "Player")
        {
            StopCoroutine(PlayerDamage());
        }
    }

IEnumerator PlayerDamage()
{
    gameObject.GetComponent<PlayerHealthManager> ().HurtPlayer (damageToGive);
    yield return new WaitForSeconds(1);
yield return PlayerDamage();
}
}

Couldn’t make it to work, but I really apreciate the help guys