articulo y video sobre programacion basica c# para unity, como programar una sentencia if

IF Statement – Decision Control Structure

Introduction

The IF statement allows us to make a decision based on whether a condition is true or false.

The simple decision is to perform an action if the condition is true and otherwise do nothing. The double decision allows us to perform a second action if the condition is false.

In the following video you can see how to define an if statement in C# language with examples in Unity.

Script from the video

Below you can download the script to test the different ways to declare an If statement.

Script de prueba de la Estructura de Control Alternativa IF

Ways to express the logical condition

The simplest way would be to use a boolean variable in the condition, but this is not the only way.

Logical Expression

Another way to do this is to create a logical expression using operators that determine whether the condition is true or false.

In the video I proposed the following example: “We can be hungry or not, if we are hungry there are two ways to eat, one is to be in the house and also have food or if not the other way is to be in a store and have money”.

With these assumptions we can create a logical expression that determines whether we eat or not. We can see it below.

weAreHungry && ( (insideHouse && weHaveFood) || (insideFoodStore && weHaveMoney) )

This expression will be true when we are in a position to eat and therefore we can use it as a condition of an if statement.

Method that returns a logical value

A method is a function that we can execute using its name, for more information see Modularization and Methods in Programming. If we have a method that returns a boolean value, its execution is equivalent to having e this value, so we can use this as a condition for an IF statement.

In the video I define a method called “ShouldWeEat()” that returns the value of the boolean expression.

Logical Expressions using other types of variables

Using the comparison operators (AND, OR, >, <, >=, <=, etc) we can create logical expressions using other types of variables such as integers, floats, characters, we can also compare strings. In the video I use as a condition the following expression:

money >= foodCost

If the money we have is greater than or equal to the cost of the food we will be able to buy it, otherwise we will not be able to.

Logical expression combining methods and operators

We can combine the two previous cases, if we have a method that returns an integer value for example, we can compare the execution of this method with another value and create a logical expression.

Leave a Comment

Your email address will not be published. Required fields are marked *