Check Trigger on Start then despawn

So i have made a ground slam ability for my 2D Platformer. It works by pressing a button, the character slams to the ground then knockups and damages enemies along the ground. Here is my code for the checker object that spawns when the character hits the ground:

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

public class SlamKnockupChecker : MonoBehaviour
{
    public float damage;
    public float force = 10f;
    public float lifeTime = 0.05f;
    void Start()
    {
        Destroy(gameObject, lifeTime);
    }

    public virtual void OnTriggerEnter2D(Collider2D col){

       if(col.tag == "Enemy"){
           hit(col.gameObject);
       }
    }

    void hit(GameObject enemy){
        var enemyScript = enemy.GetComponent<Enemy>();
        enemyScript.takeDamage(damage);
        enemyScript.knockup(force);
    }

}

It works fine however is a little messy. I’m worried that if the lifetime is too long, enemies can jump/hit the checker before it despawns, and if its too small it won’t register hits. Is there a cleaner way to do this? I don’t think i can use physics2d.overlap as the collider needs to be a specific size with specific dimensions.

Cheers.

But you can specify collider size and dimensions in Physics2d.Overlap. Otherwise you might keep as HasSet of already hitted enemies or you can have hit object id int field in enemy class and make it ignore hits coming sequentally from the same source.

1 Like