1
\$\begingroup\$

I am trying to get my enemy to take damage, however it is not working. I know the reason: the box colliders on not triggering the OnTriggerEnter message. I do not know why. Here is my code:

using UnityEngine;

public class EnemyBaseScript : MonoBehaviour
{
    public float health;   
    private Weapon weaponGettingHitBy;

    private void OnTriggerEnter(Collider col)
    {
        Debug.Log("OnTriggerEnter was called");
        if (col.gameObject.CompareTag("Weapon"))
        {
            weaponGettingHitBy = new Weapon(
               col.gameObject, 
               col.gameObject.GetComponent<WeaponBaseScript>().damageDealing
            );            
            health -= weaponGettingHitBy.damageDealt;

            Debug.Log("Took damage from weapon.");
        }   
    }
}


The code for weapons


using UnityEngine;

public class WeaponBaseScript : MonoBehaviour
{
    public float damageDealing;
}

Images of the box colliders:

(I know that some of the box colliders are off it is because I was testing around, assume all are enabled)

The sword

goblin

\$\endgroup\$
0

1 Answer 1

7
\$\begingroup\$

As you can see from the Collision action matrix in the documentation:

Trigger messages are sent upon collision

Static
Collider
Rigidbody
Collider
Kinematic
Rigidbody
Collider
Static
Trigger
Collider
Rigidbody
Trigger
Collider
Kinematic
Rigidbody
Trigger
Collider
Static Collider Y Y
Rigidbody Collider Y Y Y
Kinematic Rigidbody Collider Y Y Y
Static Trigger
Collider
Y Y Y Y
Rigidbody Trigger
Collider
Y Y Y Y Y Y
Kinematic Rigidbody
Trigger Collider
Y Y Y Y Y Y

In order to generate an OnTriggerEnter(Collider other) message, at least one of the colliders involved has to have the isTrigger flag set, and at least one of the objects involved has to have a Rigidbody attached (either at the same level or in one of its parents).

Colliders with no Rigidbody are considered "static" - the engine expects they will not move, and so it does not check for collisions between them. You should always use a Rigidbody on physics colliders that you will be moving. If you don't want the physics engine to integrate their velocity automatically, use the kinematic mode so you can keep full control of their movement while still getting collision checking.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .