How to make a tick speed for heart health system?,How to make a tick speed for health script?

I’m making a 2D game using the hearts system, every time my player collides with an enemy, one point of health is deduced. The problem is, every time my player collides, the health is reduced super quickly, killing the player in 1 or 2 seconds. How do I make it so that I can have a tick speed or a moment of invincibility so that my player doesn’t automatically die when colliding with an enemy?

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

public class Health: MonoBehaviour
{

	public int health;
	public int numOfHearts;

	public Image[] hearts;
	public Sprite fullHeart;
	public Sprite emptyHeart;
	
	void Update(){
		
		
		if(health > numOfHearts){
			health = numOfHearts;
		}
		
		for (int i = 0; i < hearts.Length; i++) {
			
			if(i < health){
			hearts*.sprite = fullHeart;*
  •  } else {*
    

_ hearts*.sprite = emptyHeart;_
_
}_
_
if(i < numOfHearts){_
_ hearts.enabled = true;
} else {
hearts.enabled = false;
}
}*_

* }*

* private void OnCollisionEnter2D(Collision2D collision) {*
* if (collision.gameObject.CompareTag(“Enemy”)) {*
* health–;*
* }*
* if(health <= 0){*
* Destroy(gameObject);*
* }*
* }*
}

Hi @Jollymello9,

You can use the time difference as well, see here.

Code example (untested)

float lastTime = 0;
float threshold = 5;
voidOnCollisionEnter2D(Collision2D collision){
  if(Time.time - lastTime > threshold  && .. compareTag("Enemy")){
    health--;
    lastTime = Time.time;
  }
  ..
}