- Home /
Trying to create a function that returns a bool
Just trying to make a simple function that detects whether or not the user is touching the ground. Getting the error "Assets/Scripts/wallriding.cs(16,10): error CS0161: `wallriding.CheckIfMidAir()': not all code paths return a value". I know it's something to do with my if/else conditioning, but what do i need to change here?
void Update () { CheckIfMidAir(); }
bool CheckIfMidAir()
{
if (Input.GetKeyDown(KeyCode.T))
{
Vector3 downward = transform.TransformDirection(Vector3.down) * 10;
Debug.DrawRay(transform.position, downward, Color.green, 500f);
print("bahh");
Ray ray = new Ray(transform.position, transform.up * -1);
RaycastHit hit;
float distance = 18f;
Physics.Raycast(ray, out hit, distance);
if (hit.distance > 1f)
{
print("offground");
return (true);
}
else
{
print("onground");
return (false);
}
}
}
Shouldn't it be yield return? Or is that just for IEnumerators?
Answer by ShadyProductions · Jul 25, 2017 at 08:17 AM
Your method needs to return something, in the case that the T key was never pressed, you will never return anything, so you should add a default return. It's actually alot cleaner if you do it like this:
private bool CheckIfMidAir()
{
Vector3 downward = transform.TransformDirection(Vector3.down) * 10;
Debug.DrawRay(transform.position, downward, Color.green, 500f);
print("bahh");
Ray ray = new Ray(transform.position, transform.up * -1);
RaycastHit hit;
float distance = 18f;
Physics.Raycast(ray, out hit, distance);
if (hit.distance > 1f)
{
print("offground");
return (true);
}
else
{
print("onground");
return (false);
}
}
And then you call the method when you press the key.
if (Input.GetKeyDown(KeyCode.T))
{
var inMidAir = CheckIfMidAir();
if (inMidAir) {
//Do something
}
}
I feel dumb, but i'm glad I asked. This helped me a lot, thanks :^)
Answer by paul_hayes · Jul 25, 2017 at 08:31 AM
Can I just add that if you are returning a boolean, and you have a boolean evaluation in an if statement. You can shorten your code significantly by just returning that evaluation. As so:
private bool CheckIfMidAir()
{
Vector3 downward = transform.TransformDirection(Vector3.down) * 10;
Debug.DrawRay(transform.position, downward, Color.green, 500f);
Ray ray = new Ray(transform.position, transform.up * -1);
RaycastHit hit;
float distance = 18f;
Physics.Raycast(ray, out hit, distance);
return hit.distance > 1f; // return the result of the evaluation, so returns true if hit.distance > 1f
}