OnTriggerEnter and OnTriggerExit behaving unexpected
void Start()
{
objects = 0;
}
// Update is called once per frame
void Update()
{
Debug.Log(objects);
}
void OnTriggerEnter(Collider col)
{
objects ++;
Debug.Log(col.name);
}
void OnTriggerExit(Collider col)
{
objects --;
Debug.Log(col.name);
}
If I add this script to a prefab that I have got and I move it into other objects it should show me how many objects it is colliding with. It does that but for some reason it says there is always 0 too. For instance I make sure the object collides with 3 other objects, it will debug saying 3, but at the same time it also debugs 0. its like every frame it says 0 and 3.
So for instance when I add a simple boolean saying: if(Objects == 5){ thisBoolean = true }, it will never actually set it to true, even if I make it collide with 5 objects, it will set it to true and then false again in the same frame.
I have no clue how to get this to work properly. I am pretty certain I had the code working on an earlier Unity version, but now at 5.1 it doesn't seem to work.
Please help me get rid of my headache :)
Answer by warrenblyth · Nov 03, 2015 at 09:09 PM
@Smurfj3 you might need to use FixedUpdate instead of Update? As i understand it FixedUpdate() only fires when physics have been updated. Update() fires as fast as Unity can, so it may updating so fast that it gives you the number of objects collided with both before and after the physics (trigger) is calculated.
All I can say is I love you, this thing was giving me a headache because at an earlier version of unity I had the script working fine so I couldn't figure it out, but that fixed it. Awesome! Thank you so much
Your answer
Follow this Question
Related Questions
OnTrigger Problems Between Colliders Issue 1 Answer
C# - How can i solve this door problem in script? Can someone help me? 1 Answer
math.Lerp not correct? 1 Answer
Help to play music whenever the character enters a GameObject... 1 Answer
OnTriggerExit2D doesn't work when one of gameObject setActive false. 0 Answers