Keep touching object ?

Hi
I’m using this code to make my object lose healthy points.

    void OnCollisionEnter(Collision collision) \\ or void OnTriggerEnter(Collider other)

{
       
            if (collision.gameObject.CompareTag("enemy"))
            {
                healthy -= 10f;
                HBar.fillAmount -= 0.1f;

            }

The problem is work when enemy object touch me once only but what if he keep touching me ?
How to solve this ?

When you say ‘keeps touching me’, are you referring to staying within touching distance? Or does the enemy move away and then return?

If you’re talking about staying close you could use something like the following:

public float timeToNextHit = 3f; // time in seconds until next hit
public float timeNextHitIsAt;

public void OnTriggerStay(Collider other)
{
  if (other.CompareTag("Player") && time.TIme >= timeNextHitIsAt)
  {
    // this enemy has hit the player
    GameObject.FindWithtag("Player").GetComponent<Player_HealthScript>().ReduceHealth(10f);
    timeNextHitIsAt = time.Time + timeToNextHit;
  }
}

First of all, not that this uses ‘OnTriggerStay’ and not ‘OnTriggerEnter’, so it will keep getting called for as long as the player (or other object) is within range of the trigger.

Second I’d recommend this code go on the enemy, so that you can have several enemies hitting the player/NPC/random object. Also please note that I don’t have Unity on the PC I’m sending this from… so ‘GameObject.’ find function is probably wrong. Use the autocomplete one. And change the tag search to whatever it is that you’re wanting to take health from.

You will also have to change ‘Player_HealthScript’ to whatever script you are using to handle the player’s/NPC’s/random object’s health and change the function to whatever you want to use.

Thank you Tset. OnTriggerStay is what i need :sunglasses:
[solved]

1 Like