Hey guys, not sure if this is a scripting issue or if I’ve implemented something wrong with the colliders, but here it goes:
All I want is a simple platform trigger that registers when the player steps on it and when they get leave.
I have BoxColliders with IsTrigger on both the platform and the player and in general everything works okay.
However there are some strange edge cases where the OnTriggerExit happens immediately after the OnTriggerEnter. Once I’ve even managed to stand in a place where it constantly went from Enter to Exit to Enter etc. without the player moving at all!
So I put position outputs in the debug text and the positions of where the Enter/Exit happens is in really strange places, nowhere near the trigger volume!
Initially I put a cooldown on the trigger volume, so it could only trigger every second but that doesn’t solve the issue of the Exit triggering for some reason when it shouldn’t.
Here’s my code for the platform:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TriggerScript : MonoBehaviour
{
public Collider player;
public Material activeMaterial, inactiveMaterial;
public float TriggerVolumeCooldown = 1f;
//private int i;
private Renderer m_Renderer;
private bool m_IsOnCooldown;
private float m_CooldownStartTimestamp;
// Start is called before the first frame update
void Start()
{
m_Renderer = GetComponent<Renderer>();
m_Renderer.material = inactiveMaterial;
m_IsOnCooldown = false;
}
void OnTriggerEnter(Collider collider)
{
//i++;
if (collider == player && !m_IsOnCooldown)
{
print(" Player entered " + collider.name + " CD: " + m_IsOnCooldown + " xyz: " + collider.GetComponentInParent<Transform>().position);
m_Renderer.material = activeMaterial;
m_IsOnCooldown = true;
m_CooldownStartTimestamp = Time.time;
}
else
{
print("cooldown");
}
}
void OnTriggerExit(Collider collider)
{
//i++;
if (collider == player)
{
print(" Player left " + collider.name + " xyz: " + collider.GetComponentInParent<Transform>().position);
m_Renderer.material = inactiveMaterial;
}
}
// Update is called once per frame
void Update()
{
if (m_IsOnCooldown)
{
if (Time.time - m_CooldownStartTimestamp > TriggerVolumeCooldown)
{
m_IsOnCooldown = false;
}
}
}
}
So multiple questions, I guess:
- Why is the enter/exit “flicker” happening - is it the colliders?
- Why is the enter/exit position in such a strange place?