- Home /
Faulty use of else within a function?
So I have this script that will send a raycast to check if the player is grounded, it seems to check when the player is grounded, but it seems like it doesn't print out when it's not grounded. I think I am using the else{ in a wrong way.
Here's the script:
var isGrounded : boolean = false;
function Update () {
var down = transform.TransformDirection(Vector3.down);
var chkGround : RaycastHit;
Physics.Raycast(transform.position, down, chkGround, 0.5);
if(chkGround.collider !=null){
if(chkGround.collider.gameObject.tag == "ground"){
Debug.Log("GROUNDED!");
isGrounded = true;
}
else{
Debug.Log("NOT GROUNDED!");
isGrounded = false;
}
}
}
I am not sure what I am doing wrong. Any help is appreciated :)
Does either of the objects have the "is trigger" option enabled in the inspector? I also suggest using the method OnTriggerEnter to handle the check.
Answer by clunk47 · Dec 05, 2013 at 10:05 PM
Put your Raycast in an if() statement, so you're only checking the tag of a collider if there is something beneath your object. If tag != ground, grounded is false. If tag == ground, grounded is true. If no raycast hit beneath object, grounded is false. Try this:
var isGrounded : boolean = false;
var down : Vector3;
var chkGround : RaycastHit;
function Update ()
{
down = -transform.up;
if(Physics.Raycast(transform.position, down, chkGround, 1))
{
if(chkGround.collider.tag == "ground")
isGrounded = true;
else
isGrounded = false;
}
else
isGrounded = false;
if(isGrounded)
Debug.Log("Grounded!");
else
Debug.Log("Not Grounded!");
}
Answer by violence · Dec 05, 2013 at 09:42 PM
if(chkGround.collider !=null)
Here youre checking that its colliding with something, which means no "Not Grounded" statement. Its not going into the next if statement if it isnt colliding with anything. You have to take the else statement out of the 2nd if statement. Simply add another bracket at line 20. That should do the trick.
Your answer
![](https://koobas.hobune.stream/wayback/20220613123524im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Need help with If/else statement. 1 Answer
else for an entire function 1 Answer