Home > Net >  OnTriggerEnter2D not working for my enemy health system
OnTriggerEnter2D not working for my enemy health system

Time:01-15

I have a projectile and an enemy, but I want the enemy to decrease the heath variable when it touches the projectile.

I tried to shoot projectiles but it did not decrease the health.

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

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

public class Health : MonoBehaviour
{
    public int startHealth = 20;
    public int health;
    // Start is called before the first frame update
    void Start()
    {
        health = startHealth;
    }

    // Update is called once per frame
    void OnTriggerEnter2D(Collider2D col)
    {
        Debug.Log("Hit");
        if (col.gameObject.tag == "PlayerProjectile")
        {
            health = health - 1;
        }
    }
    void LateUpdate()
    {
        if (health < 1)
        {
            Destroy(gameObject);
        }
    }
}

CodePudding user response:

You're probably missing one or more things:

  1. A Rigid body inside both your bullet and your enemy.

  2. A collider (non-trigger) inside both game objects.

  3. The layer collision matrix must match between both objects (you can learn more of this inside this document: https://docs.unity3d.com/Manual/LayerBasedCollision.html)

  4. If the bullet is too fast, you must change the "Collision Detection Mode", also, you can learn more here: https://docs.unity3d.com/ScriptReference/Rigidbody-collisionDetectionMode.html

I hope I help you!

  • Related