- Home /
making a variable (var) false when not colliding with a trigger.
hi, i have this script which is meant to have 'OnLand' true when inside the trigger collider (which it does fine) but i want it to be false when not inside the trigger collider. this is my script:
var OnLand = false;
function OnTriggerEnter (hit : Collider) {
if(hit.gameObject.tag == "area"){
OnLand = true;
}else{
OnLand = false;
}
}
any ideas? thanks for your time...
Answer by AdamOwen · Jul 18, 2011 at 06:03 PM
Use OnTriggerExit
var onLand = false;
function OnTriggerEnter (hit : Collider) {
if (hit.gameObject.tag == "area") {
onLand = true;
}
}
function OnTriggerExit (hit : Collider) {
if (hit.gameObject.tag == "area") {
onLand = false;
}
}
Your current code will only set onLand to false when you hit a trigger that is not tagged "area", otherwise it will continually be set to true even if you're not colliding with it anymore.
You only need:
function OnTriggerExit()
{
onLand = false;
}
for OnTriggerExit().
While that does work, I didn't want to make any assumptions on the usage of triggers in a specific game and not checking the tag when you exit the trigger will not always function as expected.
Imagine two triggers side by side and you are entering them from the left. If the second trigger you enter is the one tagged "area" the variable will be set to true. As you are passing through, as soon as you exit the first trigger the variable will be switched back to false despite still being inside the "area" trigger. This will happen both if the triggers touch eachother, or if they penetrate.
To avoid this I'd suggest using OnTriggerStay to make sure the variable is constantly set.