Bool wont return to false
using UnityEngine;
using System.Collections;
public class AFPCCrouchChecker : MonoBehaviour
{
public bool anythingAbovePlayer = false;
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag != "Player")
{
if (other.gameObject != null)
anythingAbovePlayer = true;
else
anythingAbovePlayer = false;
}
}
}
In that code my bool is working to set it self true, but it wont turn back to false. I can set false while in game in the inspector but the else block just won't work. I don't know why?
other.gameObject
will ALWAYS be non-`null`...so it's never going to be set to false
if it were null
, then you'd get an error on the previous if
statement (line 10 in your code)
So, how can I get it to check if any object is in my collider?
Answer by Yuvii · Dec 11, 2015 at 02:16 PM
OnTriggerEnter is a function called only on the frame where something entered in the trigger. So when there's nothing in the trigger, it won't call the function.
change your code to have something like that
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag != "Player")
{
anythingAbovePlayer = true;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag != "Player")
{
anythingAbovePlayer = false;
}
}
but if more than one things can be in the trigger at the same time you'll need to declare a counter like this
int counter = 0;
void Update(){
if(counter > 0)
anythingAbovePlayer = true;
else
anythingAbovePlayer = false;
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag != "Player")
{
counter++;
}
}
void OnTriggerExit(Collider other)
{
if (other.gameObject.tag != "Player")
{
counter--;
}
}
Thank you so much for helping me fix this problem :)