Lesson 12 - Floats, Bools and Casting

Tutorial Series: Introduction to Unity with C# Series

Previous Article  |  Next Article


Transcript

We looked at "strings" and "ints". Strings being sequences of characters and ints simply being whole numbers. Now let's look at numbers with decimal places this type being the type "float". Actually, for decimal values there are "floats" and there is another type called "double". But doubles take up larger memory registers and give you double the accuracy hence the name. In other words, a lot of decimal places, but I don't anticipate we will need to use doubles for numbers with decimal values. We can pretty much accomplish everything we need with simply using floats. You declare floats in pretty much the same way you declare ints. Let's do that. Let's go to Visual Studio.

Actually, before we do so, let me show you something really neat here to keep your code nice and neat and tidy. You can minimize stuff that isn't relevant for you to have to see anymore. You can just minimize it by pressing this little plus/minus box right here in that whole code block. This code block with all those commented out portions, it has just got a little bit unwieldy for our custom method called MyMethod(), so why don't we just minimize that? Actually, since we don't care about seeing the output for that MyMethod() being called and output to Unity, we can just comment that out.

Now let's make another method. Now we can just start from scratch pretty much. We will call it MyMethod2(). I am not the most creative person in the world, necessarily. Sorry with my naming conventions, but anyways we will understand it. That is a separate method and we will call it, up here in the start method just as before, MyMethod2(). Alright? In this method, our new method definition, our blank slate where we write new instructions, let's declare a float variable. Float x. That just sets aside that variable container. Nothing in it yet, as we did before. We can put a decimal value now in there so let's just say "1.9" arbitrarily and output that to the Debug.Log() just as we have been doing previously. Oh, I have an error. What is my error? Oh, silly me, I forgot that for whatever reason Unity strictly enforces putting the ‘f’ post-fix after a float value or else it just won't work. I am not entirely sure why that it is. It is kind of unique with Unity. The rest of C# you don't necessarily have to do that, but anyways now it should work. There you go, 1.9 so now we have a decimal value being output. Mind-blowing stuff right?

Here is the thing: sometimes you have an int and you expect it to return a decimal value when say, a division takes place and there will be a fraction at the end of that calculation, but you start with an int. Let's look at what happens when you try to divide an int value and expect to have the result being a decimal, let's look at what happens. Type in this... "x divided by y", so we expect to see x divided by y, 3/2, we expect to see the result output as what? 1.5, right? So, we go to unity, what do we get? We get 1. That is a curious result, why do you think we get 1? The reason again, is we are strictly dealing with whole numbers, so if we get a decimal result after the calculation of two whole numbers, the compiler just ignores it, it doesn't round it off, it just chops off, or another word is truncates, the decimal remainder and leaves us with the whole number, because we are dealing with only whole numbers, ints, it gives us a whole number at the end of the calculation.

That is a bit of a problem, if we start with floats there is of course no issue, if we do the calculation, the exact same calculation but just change this to float instead of int, and remember f at the end of the values, a peculiarity from Unity, if we do that it is no problem, we have 1.5, that is what we are expecting, but this can be a problem sometimes because sometimes we start with integers, we didn't realize that we want to end up with a decimal value at the end of that, so right away we confront a bit of an extra effort in forethought required on our part due to the type-strictness of C#. It is not a bad thing because as the old saying goes, "With one hand giveth and with the other hand taketh away.” You know what I mean. You may be wondering if to solve this problem, maybe we can convert the number int variable to one that does allow decimal value, essentially convert that into a float, right? What is so hard about that? Turn that 3 into 3.0, turn that 2 into 2.0 for example. As I said, we can avoid this issue by just starting with floats but just to illustrate if you do start with an int, you can achieve this conversion with something called casting. Let's show you what that is exactly, let's put those back to ints.

Conversions in coding have multiple pads to achieving that end result, it is not always the same, but in this case it is a very simple process called casting because the underlying data types are very similar, integers and floats just aren't that different. We can perform this conversion by using the option to cast from one value type to another, from int to float, in order to do that we simply put in parentheses the variable type that we want to convert to. Let's illustrate this a bit by adding a third variable to store the result of our calculation, hopefully it will make it a little bit easier on the eyes as well. Let's take it out at first, let's make a third variable, and we want it to be a float, z, and we will assign to it the casting of x to a float prior to the calculation of the cast of float to y, right? We are taking 3, integer 3, to x and we are casting it to a float, we are doing the same with y and then we are storing the result to, the end result being a float, to a float called z. Now we can just simply output that to the Debug.Log() by referencing z. And what do you know? I am not lying, that is exactly how it works. A bit of simple conversion called casting, that you would have to do in this case, just to show you how that works, otherwise you can just get used to the fact that you should treat whole numbers, ints, separately from when you feel that you will need to use and have decimal places, floats, being used in that case.

One thing that might not be immediately clear here is when exactly the calculation is happening that we have here. The x divided by y, and the casting the float. Does it happen when you put z in the Log() method, is it just storing the calculation process or is it happening at the assignment stage? float z equals, and then the calculation. The answer is the calculation happens right at assignment. I kind of referenced this before, mentioning how you read from the right to left with your variables and the assignments. Just remember that the assignments are operations, so the calculation is an operation, and the equal sign is an assignment operation stuffing that end result into that variable container, in this case "z". That is a quick start on writing instructions in our methods. We declare variables that store some value in memory, and then we perform options on these variables, calculations for example, on the strings we saw the plus sign being used as the concatenation operator. We also learned how to be strictly declared with the type prefixed when we declare it.

Now looked at the int type, the float type and the string type, and we also showed you a bit of converting from int to float using casting, a really quick and simple explanation of that. Rounding out four basic value types we have in C#, let's now look at the bool value type. Bools are kind of funnily named and are so called after the logician George Bool, who predated modern computing by several hundred years, but made contributions to the formalized system of logic, the same system logic that helped build our systems of coding when dealing with evaluating statements as being either true or false. This is the same basic foundation that we use when we write code and also understand statements using natural reasoning. I know it is hip and cool to talk about things being "true for me" or "true for you", but when dealing with programming there is absolutely no such thing. These are valuated as either true or false, black or white, 0 or 1, it is binary, there is nothing in the middle, no shades of grey. You could probably guess that bools store one of two possible values.

First let's make another method definition here, keep it separate. Let's comment that out and let's go MyMethod3() and here I will show you how to declare a bool value. Let's declare a bool val, and then let's assign it, you can either give it a true value or false. That is it, that is all you have with bools. Not “truthy”, not “falsey”, not “I’m not sure”. Just true or false. Bools are really simple to understand and for this reason and for this reason, they are heavily used in conditional valuation for storing states. You can consider how you may have a platformer where you want your player one character called something like IsInvincible, you can name it whatever you want, but that sounds like a good name for it. And you may start the game with IsInvincible = false, and later you grab that power-up and in doing so it sets IsInvincible to true. You can have another set of code that evaluates that, it is maybe constantly evaluating it, and if IsInvincible is true, have a countdown counter, like we saw previously in our prototype demo project. Once that counter goes down to 0 you can flip IsInvincible to the opposite value, which is "false". It is like a simple switch functionality that you get, and bools are very good for doing that. We will be showing you that in action a lot as we look at conditionals, but I don't want to overload you too much with too much information right now, and at this point I just want to conclude our brief look at the basic set of C# value types that we will be using time and again. We have character sequences strung together, that is strings, whole number integers, ints, and numbers with decimals, floats, and for holding "true" or "false" values we have bools.

In summary, what we have learned about variables is that we prefix the variable with the data type that you are constrained to what you can store in that variable container. Then you have the user-defined label for that container, your variable name, such as "val" in this case, so that you can keep referring to it using that name throughout the rest of your code. We can perform operations on our variables with things like the assignment operator, which is the equal sign, or mathematical calculations and so on, then we can combine assignments and manipulate the values that are variable stored, hence named variable in our code. That pretty much is the gist of the four basic types that C# provides us. We put them together to make more interesting statements that we can evaluate and sometimes branch off with decision making conditionals, "If this value is true or false," remember how I showed you with bools, "then do that." By using conditionals in tandem with these different operations that we can do with variables, we can start to see how all this together forms a foundation for creating the logic of our game world. So interesting and more game-like stuff ahead with looking at conditionals. See you there


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