Why check for not touched and not for touched?

Why check for not touched in the update function like this?

void Update()
{
    if(!Touchscreen.current.primaryTouch.press.isPressed)
    {
        return;
    }

    Vector2 touchPosition = Touchscreen.current.primaryTouch.position.ReadValue();

    Debug.Log(touchPosition);
}

Isn’t it better to check if touched like this:

     void Update()
     {
         if(Touchscreen.current.primaryTouch.press.isPressed)
         {
                    Vector2 touchPosition = Touchscreen.current.primaryTouch.position.ReadValue();
                   Debug.Log(touchPosition);
         }
     }

Is there an advantage to use “return;” or did you want to teach us how to use “return;”?
If I wanted to add anything else into the update function in the future, this could cause a problem if you add it after the If-statement.
But if you use my example, you could add anything before or after the If-statement without getting in troubble.

1 Like

Using either method

if(!condition) return;
//Continue with method

or

if(condition)
{
   //perform condition based action
}

are perfectly valid, and will execute in the same amount of time.

As a rule of thumb, if you know in advance that you won’t be doing anything else with the method, then the first one is “best practice”. In cases where you will be doing something regardless of the condition, I apply the following rule of thumb:

  • If the lines you’ll be putting after the if clause are not dependent on anything within the if clause, then they probably should go before the if clause, and the first if clause should be used.
  • If the lines are dependent on the clause, then stick with the second if clause.

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

Privacy & Terms