Collider not triggered properly

Hello guys.
Here I’m having a bit of an issue. I’ve got this simple script that sets a bool true if an enemy (with a collider and a rigidbody) is in the range of the collider. It works just fine but sometimes, when I move a bit, the bool just go false even if the enemy stays within the range of the collider…
Any ideas why it happens?

the scripts :

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

public class PlayerAttacker : MonoBehaviour
{
    AnimatorManager animatorManager;

    public Collider sphereCollider;
    private Transform target;

    public bool isTargetting;

    private void Awake()
    {
        animatorManager = GetComponent<AnimatorManager>();
    }

    private void Update()
    {
        if (target == null)
            isTargetting = false;
        else
            isTargetting = true;
    }

    public void HandleAttack()
    {
        animatorManager.PlayTargetAnimation("Female Sword Attack 1", true, true);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Enemy"))
        {
            target = other.transform;
        }
    }
    private void OnTriggerExit(Collider other)
    {
        if (other.CompareTag("Enemy"))
        {
            target = null;
        }
    }

    public void HandleTargetting()
    {
        if (target == null)
        {
            return;
        }
        transform.LookAt(target);
    }
}

here a screenshot of the running game where we can see the “isTargetting” bool set to false when the enemy is clearly in the collider :

Thx in advance for the help :slight_smile:

You have 2 colliders on the player. They can trigger enter and exit separately.

1 Like

Thank you very much mate. It’s working just fine if I disable the second collider. But unfortunately I need those two colliders on my player (one for auto-targeting, one for taking damage) … do you know how to adapt my script to make the bool only triggered by the spherical one?

Yeah, fairly easy to do:

  • make public collider fields for the one(s) you actually want to hear about

  • in the trigger responder method, check if it is the one you care about by comparing it

Otherwise you can also use layers (and hence separate GameObjects to host different-layered colliders) to differentiate via a layermask or via the collision matrix in the physics setup.

1 Like

Thank you! I’ll try this out