Home>

I want to make the bullet disappear when the enemy character hits the enemy character and reduce the HP of the enemy character that hits it. In addition, since bullets are generated from the character, we want to avoid physical contact.

Error message

Even if a shot is in contact with an enemy, it will pass through without disappearing. Also, HP has not decreased.

Applicable source code

A bullet script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript: MonoBehaviour
{
    public float speed = 10f;
    // Start is called before the first frame update
    void Start ()
    {
    }
    // Update is called once per frame
    void Update ()
    {
        transform.position + = transform.right * speed * Time.deltaTime;
    }
    void OnTrigerEnter2D (Collider2D other)
    {
        if (other.gameObject.tag == "enemy")
        {
            Destroy (gameObject);
        }
    }
}

Enemy HP script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HPmanager: MonoBehaviour
{
    [Header ("HP")] public float HP;
    // Start is called before the first frame update
    void Start ()
    {
    }
    // Update is called once per frame
    void Update ()
    {
    }
    void OnTrigerEnter2D (Collider2D other)
    {
        if (other.gameObject.tag == "bullet")
        {
            if (HP>0)
            {
                HP-= 1;
            }
            else
            {
                Destroy (gameObject);
            }
        }
    }
}


Bullet isTrigger is checked, enemy isTrigger is not checked, Rigidbody is attached to both, and Simulated is checked.

I tried various things with reference to http://kimama-up.net/unity-trigger/, but the results did not change.

  • Answer # 1

    The name of the method defined in your code isOnTrigerEnter2D. Isn't it a spelling error?
    How about setting it to OnTriggerEnter2D?