- Home /
OnTriggerExit doesn't work when scaling collider
Hi, my name is Dawid and I'm long time reader, first time writer. After several hours I finally managed to solve the problem I had, but I still don't understand why it happens, hence this post.
Background: I have a [scene] with Enemy NPC, which has mesh collider (as a vision cone) and script with OnTriggerEnter and OnTriggerExit events. Script also has a variable (named "visionRange"), which allows scaling of mesh collider's parent, so that I can control AI vision range in real time.
Problem: When player enters mesh collider, everything works fine - OnTriggerEnter is executed. However when player leaves mesh collider, OnTriggerExit does not execute.
Unsatisfactory solution: Now what is interesting, the problem only occurs when "visionRange" variable is set to 3.0f. When variable value is set to i.e. 2.0f or 4.0f, everything works as intended.
Actual question: Can someone explain to me why such a problem occurs?
Script:
public float visionRange = 3.0f;
float previousVisionRange = 1.0f;
AiAttributes aiAttributes;
void Update ()
{
if (visionRange != previousVisionRange) {
//if [visionRange == 3] - OnTriggerExit does not work;
//if [visionRange == 2] - everything is fine
transform.localScale = new Vector3 (visionRange * 0.45f, visionRange * 0.45f, 1f);
previousVisionRange = visionRange;
}
}
void OnTriggerEnter(Collider collider)
{
if (collider.name == "Player" && !aiAttributes.isTargetVisible) {
aiAttributes.isTargetVisible = true;
aiAttributes.target = collider.gameObject;
}
}
void OnTriggerExit(Collider collider)
{
if (collider.name == "Player") {
aiAttributes.isTargetVisible = false;
aiAttributes.target = null;
}
}
Scene image: