Yes there are many questions and answers concerning similar topics, but funny enough I have not gotten a satisfying answer out of any of those posts.
The title describes the entire problem I am experiencing, so here is the code. By the life of me I do not understand why this is called multiple times when the collider (isTrigger=true) passes through my CharacterController (maybe the problem lies in this?).
Edit: It has come up several times, so to clarify:
-
The EnemyAgent Script does not use
the damageDealt boolean - it is only
used to store it as a public variable. -
There is no other collider apart
from the CharacterController
attached to the Gameobject in
question. -
Also of note might be that the
triggerenter/triggerexit functions
are called many, many times and not
just twice. -
Since there are checks in place the
single most important question is:
Why is the OnTriggerExit() method called prematurely - before leaving
the actual collider?using UnityEngine; using System.Collections; using System.Collections.Generic; public class HitBox : MonoBehaviour { PlayerHealth playerHealth; void Awake () { playerHealth = this.gameObject.GetComponent <PlayerHealth> (); } void OnTriggerEnter (Collider other) { if(other.gameObject.tag == "EnemyWeapon"){ EnemyAgent thisAgent = other.gameObject.GetComponentInParent<EnemyAgent>(); if (thisAgent.damageDealt) return; if (thisAgent.attacking) { thisAgent.damageDealt = true; playerHealth.TakeDamage (thisAgent.attackDamage); Debug.Log (thisAgent.ID + " in"); } } } void OnTriggerExit(Collider other){ if (other.gameObject.tag == "EnemyWeapon") { EnemyAgent thisAgent = other.gameObject.GetComponentInParent<EnemyAgent>(); if (thisAgent.damageDealt) { thisAgent.damageDealt = false; Debug.Log (thisAgent.ID + " out"); } } } }
If you are wondering why the specific enemy agent is only sought after the collider is determined - it’s done this way in order to have several enemies attack the player at the same time.
Please help…