- Home /
How can I reset a function (boolean), like ON and OFF?
I have a boolean calles isgrounded, what I want to do in the function is to reset it, so that it turns true or false, if (hitInfo.distance < 0.5f)or (hitInfo.distance > 0.5f).
Somehow it is not working, but the raycasting works fine, I just dont know how to reset it. Because the order of the code only reads the last condition (if) and assumes it is true or false, but never resets it.
This is my function:
void IsGrounded()
{
RaycastHit hitInfo;
if (Physics.Raycast(rb.transform.position + Vector3.down * 1f, Vector3.up * 5f, out hitInfo, Mathf.Infinity))
{
if (hitInfo.distance > 0.5f) // Change .1f to what you need
Debug.DrawRay(rb.transform.position + Vector3.down * 1f, Vector3.up * 5f, Color.blue);
isgrounded = false;
if (hitInfo.distance < 0.5f)
Debug.DrawRay(rb.transform.position + Vector3.down * 1f, Vector3.up * 5f, Color.red);
isgrounded = true;
}
}
Are you trying to set isgrounded to false when hitInfo.distance > 0.5f and to true when hitInfo.distance < 0.5f?
Right now both your isgrounded sets will be called every time in that function because they are not truly inside the if statement.
thanks, so how do i fix it? can you put it on code please?
Answer by Baste · Dec 05, 2014 at 03:43 PM
Add braces to move the assignments inside the if-statements:
if (Physics.Raycast(rb.transform.position + Vector3.down * 1f, Vector3.up * 5f, out hitInfo, Mathf.Infinity)) {
if (hitInfo.distance > 0.5f) { // Change .1f to what you need
Debug.DrawRay(rb.transform.position + Vector3.down * 1f, Vector3.up * 5f, Color.blue);
isgrounded = false;
}
if (hitInfo.distance < 0.5f) {
Debug.DrawRay(rb.transform.position + Vector3.down * 1f, Vector3.up * 5f, Color.red);
isgrounded = true;
}
}
You should also do some more coding tutorials, this is rather basic.
thanks, it works, I am perplex, how do you know that? It is not that basic. But thanks. I am kinda stupid you know :)
Only the first instruction after an if, for, while etc. will be executed when not enclosed in curly bracktes { } ;)
Your answer
![](https://koobas.hobune.stream/wayback/20220613173259im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to develop a script that substitute a gameobject position with my character? 0 Answers
Help with raycast from a ragdoll 0 Answers
Raycast2D Only returns true 1 Answer
Gravity makes player slide on any slope!!! Check if rigidbody Isgrounded not working 0 Answers
ground check isnt working...HELP! 2 Answers