Search code examples
c#unity-game-enginegame-enginegame-developmenticsharpcode

Object in Unity won't trigger, although the colliders and code are correct


Since almost a week I'm testing Unity for making games. The problem is the following: I have an enemy and a circle around the player, which both has a collider with IsTrigger active. In the code, there is an OnTriggerEnter and OnTriggerExit event for the enemy. If the enemy enters the circle of the player, a bool gets true and other things should happen. But only this happens: The enemy goes right inside the player and only then the bool gets true (I tested it many times and this is it) even though the player itself doesn't have a collider, only the circle around it (the player has of course a character controller, but this can't be a trigger, can it?)

The enemy has a simple AI and always walks to the direction of the player so maybe it only triggers, when he is there. Because this it what seems to happen. The code is right here:

public GameObject thePlayer;
    public GameObject theEnemy;
    public float enemySpeed = 0.01f;
    public bool attackTrigger = false;
    public bool isAttacking = false;

    void Update () {
        transform.LookAt(thePlayer.transform);
        if (attackTrigger == false)
        {
            enemySpeed = 0.01f;
            theEnemy.GetComponent<Animation>().Play("walk");
            transform.position = Vector3.MoveTowards(transform.position, thePlayer.transform.position, enemySpeed);
        }
        if (attackTrigger == true && isAttacking == false)
        {
            enemySpeed = 0;
            theEnemy.GetComponent<Animation>().Play("attack");
            StartCoroutine(InflictDamage());
        }

    }

    void OnTriggerEnter()
    {
        attackTrigger = true;
    }

    void OnTriggerExit()
    {
        attackTrigger = false;
    }


    IEnumerator InflictDamage()
    {
        isAttacking = true;
        yield return new WaitForSeconds(1.1f);
        GlobalHealth.currentHealth -= 5;
        yield return new WaitForSeconds(0.2f);
        isAttacking = false;
    }

This Code actually belongs to Jimmy Vegas. I'm learning from his YouTube tutorial und in his video it worked fine. That's why I'm so confused.

Edit: The enemy ignores my player. Even when I add the collider to the player itself, it won't trigger. If I have the IsTrigger from the enemy turned off, he just glitches me away. I don't know what this is.


Solution

  • https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerStay.html

    " Trigger events are only sent if one of the colliders also has a rigidbody attached "

    Both GameObjects must contain a Collider component. One must have Collider.isTrigger enabled, and contain a Rigidbody.