Changing a bool if colliding and setting back to false if not

Hey so I am trying to change a bool based on whether a gameobject is in c collider that is set as a trigger. The problem is that my code works to set my bool to true but it does not set back to false when it is not in the trigger.

void OnTriggerEnter2D(Collider2D ground){

			if (ground.gameObject.tag == "ground") {
						Debug.Log ("I'm colliding with ground");
						onground = true;
						
				} else {
					onground = false;
				}
		
		   }

You need to explain how you are trying to use this functionality. The above code is only going to be called if the two objects are intersecting. I'm guessing that you want to set onground = false in 'OnTriggerExit2D()', or use some other method to detect the ground.

–

1 Answer

1

You would want to set it to false in the last controllable step of the frame (LateUpdate) and set it to true if the object is inside the trigger.

void OnTriggerStay2D(Collider2D other)
{
    if (other.tag == "ground")
    {
        onground = true;
    }
}

void LateUpdate()
{
    onground = false;
}

As LateUpdate is called after every Update is executed, you can do whatever you want with that flag. Here is a link to event execution order in Unity.