Lesson 14 - If Statements Continued

Tutorial Series: Introduction to Unity with C# Series

Previous Article  |  Next Article


Transcript

Continuing on with our look at if statements. At this point, you may be wondering, “Hey, all of our if statements start "with whether or not something is true, “but sometimes we want to start "with whether or not something is not the case.” Not equivalent, for example. Yes, if statements execute their immediate code block only if the statement within the parenthesis being evaluated ends up being true, but it is perfectly logical to ask the compiler to execute that if-then code block, if it is true that the statement is false, or if it is true that the operands are not equivalent. The way I said that may sound weird, but this is actually very intuitive. We all reason like this naturally without even thinking about it. Let me illustrate by going back to where we started, but inverting the evaluation to look something like this. Actually, the first thing we should do is, we will make a whole new method definition as we did before to keep things nice and compact and clean. As before, we name it pretty much the same but add a number after it, and here we will call it by changing to that number, changing it to that method definition. Let's write in this code, if (x != 100) I am just going to put a comment there.

Remember, commenting is useful for more than just commenting out code. It is good for making notes for yourselves, which you should be doing fairly frequently, especially as a beginner. If x is not equivalent to Output the Debug.Log()X is not equivalent to 100. Surprise, surprise. Else, to catch the case that it is equivalent. We will simply call the Debug.Log() and put in the argument: x is equivalent to Save that. Go to our Unity console. Run it. "x is equivalent to 100." Here we see the exclamation, or exclamation mark operator, which is sometimes referred to by coders as “bang” in coding speak, but I don't really like saying bang, so I will just stick to saying exclamation. It can be read simply as not. You notice we draw up the second equal sign, when you pair it with the equal sign and create the not equivalent operator. I am not really sure why they chose to drop the second equal sign. It is pretty commonly represented like this in coding. It is a bit confusing, but here, this is just the combined operator of not and equivalent, which gives us not equivalent. Just remember that and you'll get used to it.

Is it true that X in this case is not equivalent to 100? No. Of course not. What happens is it drops down to the else statement. We get the same basic logic output. It is just inverted now. One interesting thing about the exclamation operator is it can be added to the binary operator, as we did here, the equivalence operator, which is binary because it checks for equivalence between 2 operands. Remember how I mentioned operands? The elements being evaluated on each side of the operator, but the exclamation operator has an added functionality in that it can be also used on a single operand, making it also a unary operator. So, binary when it is operating on 2 operands, unary as in uno, as in 1, when it operates on a single operator. You can add it to an entire statement even, or a bool, having the effect of flipping its value.

Let me show you how you do this, how you would add it to an entire statement in your conditional evaluation. Let's go here and write in, instead of saying "Is x not equivalent to 100," we will basically move it to the entire statement. We will wrap the statement… Sorry, not 3 equal signs, 2 equal signs. We will wrap this statement into parenthesis. We will evaluate that and then we will put the bang, sorry, exclamation operator, at the front of that entire statement. Read out, this statement would be something like, “If it is true that it is not the case that x "is equivalent to 100, then do this.”

This is kind of horrible for readability, so it is not something I'd recommend you do. I don't see it being used in this way very often, but it does make logical sense. If something is true that it is not true, it is ultimately false, right? In the end, don't worry about seeing code as confusing as this. I just wanted you to see the versatility of the exclamation mark, the not operator, and ultimately use it for readability, where it makes more sense to check for something being not the case first. We can also use the exclamation as a unary operator, as I mentioned, on bools. Remember bools? We just saw it a couple videos back. Bools have true and false built right into them, so we can easily evaluate them as follows. Let's comment out, actually let's just make another method definition for bools and call that new one now. So let's write in this. bool val = true; if (val...I will put to the Debug.Log("val is TRUE") Else, val is false. Save that. I am sure you can guess what you're going to see next. val is true. Of course. This is the same here.

What we are doing here is we are evaluating val as true or false. It is saying if val is true, then do this immediate code block. Else, fall to the else clause. This is exactly the same as doing if (val == true). You can write that. That is perfectly legal and does exactly the same thing, but it is just a little bit cleaner to just type in the bool and check if it is true. That is all that that means. We can use the exclamation as a unary operator on this, and we will first check if it is not true that it is true, which means it will only evaluate true if it is false. You will get used to that kind of way of thinking. It may seem kind of strange when you say it out loud, but it is actually pretty intuitive. Val is false. This evaluation evaluated correctly, but we kind of made it confusing. We should flip these now to get the actual correct message that we are anticipating. There we go. That is actually what we are expecting. In this case, what we are doing is we are evaluating if val is not true. That is what the exclamation mark in front of the bool is representing when it is in that if statement evaluation. It will always be represented that way.

As if that wasn't enough, exclamations are versatile even more in that they can perform an operation on the bool itself and store that result. For example, you can do this. Just comment this out and let's write in val = !val. What do you think is going to happen? We are performing operation on val now, and let's put in the Debug.Log() What do you think is going to happen now that we put this exclamation mark in front of val, which is true, making it not val, whatever value val has at that moment. Then assign it back to val. Let's run it. See if you guessed right. False. The operation here is take whatever value, whether it is true or false, that val currently holds and make it not that. In other words, the opposite of that value. This can be very useful in programming or any programming where you want a simple toggle switch. You can just keep toggling back and forth. Let's do something like this to illustrate that in action. Actually, what I will do is I will just copy and paste this, because it is going to be exactly the same. If you are understanding what this is doing correctly, try to anticipate the output here.

I am just going to save it and run it and let's see if you anticipated it correctly. It is going to output every time it flips. It first flips from true to false, then it flips to true, and then it flips to false again. That is the switching that I was talking about. It starts off as true, then it flips it, not true. Stores it back. That will be false. Then it flips false back to true, stores that. We get true. Then it takes the true finally again, flips it back to false, stores it, and we finally get false. With that, I showed you some fairly basic examples of if statements in action. But there will often be a case where you will want to evaluate a bunch of different things. Remember when I showed you how to create your own order of operations by using parenthesis in math operations? Well, here again we will see their use in creating more complex conditional statement clauses. Let's write some more code. Let's create another method definition for this. Write in this. What we are going to do is we are going to simulate a button being pressed, because right now we are not actually using the Unity input mechanism to register button presses, so we will just simulate that a button is being pressed.

I am going to put a comment here, “Simulating button presses,” Just so we remember what it is we are doing. Type in bool isButtonAPressed, arbitrarily named true. Set it to true. Then bool isButtonBPressed. Set that also to true. Then let's make a little conditional to evaluate this state. If (isButtonAPressed && isButtonBPressed), && stands for and, so if both of these buttons that we are simulating are being pressed, will output to the Debug.Log()Our button conditional evaluates as true. I am going to copy that. Go a little quicker. Else and then same thing, but it evaluates as false. We will save that and run it. Both buttons are simulated as being true, which is that they are being pressed. It executes conditional. The button conditional evaluates as true. It executes the first if clause, because the entire statement evaluates as true if, and only if both of these are true.

If we make one false, it doesn't matter which one, they could be both false or one of them false, and then this conditional will not evaluate as true any longer. There you go. Evaluates as false. This is a very handy functionality that we'll be using a lot. Actually, we will be using it often with button presses. You don't have only && available to you. You also have or, which is another common logical operator. To represent or, we will type in the ||or turnstile I have sometimes heard it being referred to as. Which is the shift and, on my keyboard, the shift and backslash key which gives you that straight line. You just type in 2 of those and you get the or operator. isButtonAPressed = true. isButtonBPressed = false. What do you think this is going to evaluate as? Well, all it requires is that one of these is true or the other one is true. It could be both, but all it requires is one. Which one do you think it should output? Let's save it and run it. Yes. Of course. It evaluates as true, because it is true that one or the other is true. In this case, isButtonAPressed is true.


Related Articles in this Tutorial:

Lesson 1 - Who This Course is For

Lesson 2 - What to Expect from this Course

Lesson 3 - Installation and Getting Started

Lesson 4 - Starting the First Project

Lesson 5 - Prototype Workflow

Lesson 6 - Basic Code Review

Lesson 7 - Game Loop Primer

Lesson 8 - Prototyping Continued

Lesson 9 - C# Fundamentals and Hello World

Lesson 10 - Variables and Operations

Lesson 11 - Variables and Operations Continued

Lesson 12 - Floats, Bools and Casting

Lesson 13 - If Statement Conditionals

Lesson 14 - If Statements Continued

Lesson 15 - Complex Evaluations and States

Lesson 16 - Code Syntax vs. Style

Lesson 17 - Variable Scope

Lesson 18 - Object-Oriented Programming Intro

Lesson 19 - OOP, Access Modifiers, Instantiation

Lesson 20 - Object Containment and Method Returns

Lesson 21 - "Has-A" Object Containment

Lesson 22 - "Is-A" Inheritance Containment

Lesson 23 - Static Fields and Methods

Lesson 24 - Method Inputs and Returns

Lesson 25 - Reference vs. Value Types

Lesson 26 - Introduction to Polymorphism

Lesson 27 - Navigating the Unity API

Lesson 28 - Applying What You've Learned and Refactoring

Lesson 29 - Constructors, Local Variables in the Update Method

Lesson 30 - Collecting Collectibles, Items and Powerups

Lesson 31 - Spawning and Managing Prefab Powerups

Lesson 32 - Implementing Powerup State Logic

Lesson 33 - Displaying Text, OnGUI, Method Overloading

Lesson 34 - Referencing Instantiated GameObjects, Parenting

Lesson 35 - Understanding the Lerp Method

Lesson 36 - Creating Pseudo Animations in Code

Lesson 37 - Understanding Generic Classes and Methods

Lesson 38 - Animations Using SpriteSheets and Animator

Lesson 39 - Working with Arrays and Loops

Lesson 40 - Debugging Unity Projects with Visual Studio

Lesson 41 - Camera Movement and LateUpdate

Lesson 42 - Playing Audio Clips

Lesson 43 - Routing Audio, Mixers and Effects

Lesson 44 - Adding Scoring Mechanics and Enhancements

Lesson 45 - Scene Loading and Game Over Manager

Lesson 46 - Understanding Properties

Lesson 47 - Controller Mapping and Input Manager

Lesson 48 - Understanding Enums

Lesson 49 - Dealing with Null References

Lesson 50 - Handling Variable Framerates with time.DeltaTime

Lesson 51 - Preparing the Project for Final Build

Lesson 52 - Final Build and Project Settings

Lesson 53 - Introduction to the Unity Physics Engine

Lesson 54 - Understanding FixedUpdate vs. Update

Lesson 55 - Movement Using Physics

Lesson 56 - Attack Script and Collision Events with OnCollisionEnter2D

Lesson 57 - Projectiles and Stomping Attack

Lesson 58 - Parallax Background and Scrolling Camera

Lesson 59 - Infinitely Tiling Background Sprites

Lesson 60 - OOP Enemy Classes

Lesson 61 - OOP Enemy Classes Continued

Lesson 62 - Trigger Colliders and Causing Damage

Lesson 63 - Multi-Dimensional Arrays and Procedural Platforms

Lesson 64 - Finishing Touches

Lesson 65 - Series Wrap


Comments

Please login or register to add a comment