- Home /
Ontriggerstay2d only runs 26 times in a row?
So I was running some test about OnTriggerStay2D, and I realize it only runs 26 times in a row if no position changes are made between the two colliders involved.
Here is the code, I can't see anything wrong here:
using UnityEngine;
using System.Collections;
public class TriggerTest : MonoBehaviour {
public int i;
public int a;
void Update()
{
a = i * 2;
}
void OnTriggerStay2D(Collider2D other)
{
i++;
}
}
When something enters the trigger area, "i" goes up to 26 then stops, and "a" goes upto 52 (26*2) and stops. If I move the trigger area, or the collider inside the area, it will go up again, but stop after 26 times. I tried to run a debug.log as well, and the log only runs 26 times.
Anyone have any idea why this is like this?
Answer by gtaharaedmonds · Oct 14, 2016 at 05:55 AM
Had this problem a while back. In the gameobject's rigidbody component, change the "sleeping mode" to "never sleep". This will have a hit on performance, though.
Answer by gtaharaedmonds · Oct 14, 2016 at 05:55 AM
Had this problem a while back. In the gameobject's rigidbody component, change the "sleeping mode" to "never sleep". This will have a hit on performance, though.
Answer by ElijahShadbolt · Oct 14, 2016 at 04:56 AM
Rigidbodies that aren't moving go into 'sleep mode', where they don't conduct physics updates to save processing power. This means OnTriggerStay2D and other Stay events get called for a short time, then the rigidbody goes to sleep so they no longer get called.
You can overcome this problem by only checking OnCollisionEnter/Exit, so that when an object enters the trigger it starts updating i
and when it exits the trigger it stops updating i
.
using UnityEngine;
public class TriggerTest : MonoBehaviour
{
public int i;
public int a;
private bool update_i = false;
void Update()
{
if (update_i)
{
i++;
a = i * 2;
}
}
void OnTriggerEnter2D(Collider2D other)
{
update_i = true;
}
void OnTriggerExit2D(Collider2D other)
{
update_i = false;
}
}
In this script, i
represents the number of frames that the collider is in the trigger.
You might also like to measure the change in time (in seconds) instead of frames. If so, you could change i
to a float
and update it like so: i += Time.deltaTime;