spencer harris
spencer harris

Reputation: 11

How can I make a variable (preferably boolean) that can determine whether or not a function is running?

CONTEXT

I'm making a unity game and I need to test if my player is on the ground or not, for any of you familiar with things like "OnCollisionEnter", they won't work with the way make game functions, however, "OnControllerColliderHit" works, but there is no negative/exit for this.

What I want to do is have a boolean equal true while the function is running, and once the function has stopped being called (the player is not on the ground), this boolean would turn false.

Feel free to ask if you need any additional information, or (if you are knowledgeable in unity) find a different solution regarding "OnCollisionEnter".

Thanks!

Upvotes: 0

Views: 156

Answers (1)

Milad Qasemi
Milad Qasemi

Reputation: 3059

if your problem is checking if the character is on the ground you can make a raycast from your character down to the ground and we add a margin for uneven platforms you should change this value and find the one that best suits your ground

float distanceToGround;
float margin;

 void Start(){
   // get the distance to ground
   distanceToGround = collider.bounds.extents.y;
 }

  boolean IsGrounded() {
   return Physics.Raycast(transform.position, -Vector3.up, distanceToGround +  margin);
 }

 void Update () {
   if (IsGrounded()){
     //DoSomething
   }
 }

also if your character got a character controller component attached(as you are using OnControllerColliderHit so it is definitely attached ) you can simply check grounded like this

    void Start(){
         CharacterController controller = GetComponent<CharacterController>();
      }

 void Update() {       
        if (controller.isGrounded)
            //DoSomething      
    }

Upvotes: 1

Related Questions