- Home /
onTriggerEnter2D not acting like I thought
Hey, so I was fiddling around with onTriggerEnter2D, and I succesfully wrote a script that tested if a certain collider entered the trigger, and set a static var "collide" equal to true if it did. Here was my original script:
#pragma strict
var target : Collider2D;
static var collide : boolean;
function OnTriggerEnter2D(collision:Collider2D){
if(collision == target){
collide = true;
}
else{
collide = false;
}
}
function Update () {
}
It worked, and I was able to do stuff only when collide was true in other scripts. However, once the target object left the trigger the collide var was never turned off! This makes sense, of course, since the else - false statement only comes into affect if ANOTHER collider enters the trigger. I decided to make a "called" variable to fix the problem:
#pragma strict
var target : Collider2D;
static var collide : boolean;
private var called : boolean;
function OnTriggerEnter2D(collision:Collider2D){
if(collision == target){
collide = true;
}
else{
collide = false;
}
called = true;
}
function Update () {
if(!called){
collide = false;
}
called = false;
}
I would naturally thing that this would turn collide off only when there is not a collision with the target. However, when I run the script, my collide script doesn't have any effect. Is there something I'm missing here? Is cross referencing between OnTriggerEnter and Update a bad idea? If so, is there a way to do an if(!OnTriggerEnter) or something of that effect?
Answer by Kiwasi · Jul 11, 2014 at 04:24 AM
I'm sorry to tell you, but you've gone a fair ways down the wrong path.
OnTriggerEnter is called once when the collider first enters the trigger. Then it will never run again unless the collider exits the trigger and enters it again.
The effect you are after can be achieved by using a combination of OnTriggerEnter and OnTriggerExit. This is how I prefer to do it. You can also use OnTriggerStay.
Thank you, thank you, thank you! The OnTriggerExit is the answer to the first problem I had (as opposed to the "called" variable). I can just have it turn collide off OnTriggerExit. I can't believe I hadn't thought of that! $$anonymous$$any thanks again for answering and for pointing out the other OnTrigger functions I had so carelessly forgotten about.
Your answer
Follow this Question
Related Questions
How to use OnTriggerEnter? (JS) 1 Answer
On collision between two cubes 2 Answers
BCE0044: expecting (, found 'OnGUI'. 1 Answer
OnTriggerEnter getting delay when object is moving? 1 Answer
Setting Scroll View Width GUILayout 1 Answer