Difference of changing the if statement Vs adding return inside of the statement

Often I will pause the lesson to see if I can use a bit of critical thinking to figure out the steps that the instructor will take ahead of time. I was doing so with stopping the issue of reselecting a unit instead of using the spin action. I thought the answer would be to add an && unit != selectedunit inside of the if. I attempted it and it seemed like the code was working properly, but when I resumed the video the instructor instead did another if statement inside of the already created one(at about 10:35 in the video), to return. So I’m curious what exactly are the differences between those two options? Is it minor and does roughly the same thing? I often overlook things, not having a huge background in these kinds of things so I could definitely be missing something large. Thanks for your time.

Can you pop in the two if statements in question? I don’t have the codebase completely memorized.
I will say that there are often many paths to the same goal.

It’s this here

private bool TryHandleUnitSelection()
{
    if (Input.GetMouseButtonDown(0))
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, unitLayerMask))
        {
            if (raycastHit.transform.TryGetComponent<Unit>(out Unit unit))
            {
                if (unit == selectedUnit) // <-- HERE
                {
                    // Unit is already selected
                    return false;
                }
                
                SetSelectedUnit(unit);
                return true;
            }
        }
    }

    return false;
}

In this case the solution is perfectly fine.

1 Like

Awesome. Is there any difference at all between the two options?

Behind the scenes and performance wise, no. It’s a matter of preference. Some prefer blocking and exiting a method early, and leaving the code less indented. Others prefer a positive action with the code further indented.

There are times where the if(true) {} are necessary, where there is code that must run, but also must wait until after the clause has been run. Otherwise, the net effect is the same.

Also, if this was in a loop (eg. we used Physics.RaycastAll), Hugo’s way would immediately exit the loop when we found the unit, while the other way would continue to check

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms