Lesson 10 - Variables and Operations

Tutorial Series: Introduction to Unity with C# Series

Previous Article  |  Next Article


Transcript

In that last video, I briefly mentioned our basic containment structure. Now, I have some props here as a simple illustration and to refresh your memory. We have an outer container, which is your class definition. Here you see we labeled it ‘Test.’ Alright. This container, your class, contains within it a sub-container method that is named MyMethod(). We know it is a method because it has those invocation parentheses right off the name. This container, remember, inside of it contains instruction. That is what methods contain in turn. This instruction reads, "Execute the Log() method found in the Debug class and pass in the string argument ‘Hello world’" Later on we know that somewhere else in code, it was in our Start() method actually, that we called this box by name. In other words, MyMethod() with the parentheses right after it. The compiler does the equivalent of opening up these boxes and actually executing those written instructions.

Wouldn't it be great if you could write code like this, actually writing out specific instruction in a human readable natural language like English? Well, it seems like it would be a great thing, but as it turns out natural languages are very imprecise. Sometimes meaning is hidden behind context and unconscious inference on the part of the reader is implied. Coding is a lot like a natural language, like English, in many ways. The main difference with code is it is a lot more terse and specific because we are speaking to a machine and machines are dumb. No matter what you hear about machines just getting faster and smarter, make no mistake, at the base level all machines are basically pretty dumb. They will only do what you instruct them to do exactly as you instruct them to do it. They can't infer anything and they demand that you tell them exactly what to do without ambiguity.

Take for instance an instruction in written English such as this, if I tell you to go all the way down the street and turn left until you reach the four-way stop. I am sure you can visualize those instructions without much difficulty. Most people would be able to execute that instruction without much difficulty. Think about it, it is actually full of ambiguity. A machine would have a very hard time with these instructions. You might find it trying to dig a hole in the street because, after all, you are telling it to go downwards, right? Go down the street. You are saying turn left until you reach the four way stop. Perhaps it will try to just dig a hole while turning left the whole time, going in circles. The machine will keep executing going down and turning left, pleased as punch to keep doing so until it reaches that four way stop, which we know will never happen. The machine doesn't realize there is something obviously wrong with its interpretation of the instruction. Us as humans will recognize that right away. You have to be more precise with the computer. This instruction more accurately describe to a machine would sound something like this, "Start moving south. "If at the end of the street, turn left. "If at a four way stop, stop moving." Now, that instruction seems like it says the exact same thing, but actually is being a lot more specific. Go ahead and think about that. Look at that example and think of the ways in which it is being a lot more specific. How it reduces the chance of errors occurring. Alright. This is more of the shift in thinking that you'll have to do when learning to code. Not so much in learning the language or the syntax, but it is simply being more specific in your instructions.

When we are writing computable instructions, coding in other words, we are sort of talking to the computer in a language that it understands. Telling it what to do under different conditions. Just like you communicate in natural language, like English, by stringing together nouns which are things and verbs which are actions, we do much the same in coding by creating variables which are like the nouns and performing operations on them which is like the verbs being performed on the nouns, on the things. These instructions then occur in sequence, like writing sentences in a natural language, which you then string together and form a complete paragraph. Which is analogous to an entire code block that you might write within the method definition. Let's make a couple of variables and perform a simple operation on them, forming some statements in code. When you are talking coding speak you use the term ‘statement,’ but it is much the same as writing a sentence in a natural language. Let's go over to our Test script here.

Actually, let's learn a little thing here first that is useful, and that is commenting out code. Commenting out is very useful in a lot of different ways when you don't want to delete code that you maybe want to make sure that you can go back to if you make an error. It preserves your code, but basically the compiler ignores it so when you run the script it no longer works. You can create a comment simply by putting two forward slashes in front of the piece of code that you are commenting out. When you have that comment in Visual Studio, you can comment and un-comment by clicking on these respective icons. I am commenting out and I am commenting, right? Nice handy little tool there. Let's comment this out because we are not going to need that anymore, but let's keep this MyMethod() custom method that we made to write our verbs and nouns, as we called it, variables and operations. Let's start with this, write this code. Put that in our Debug.Log() that we are familiar with at this point. Alright. Save that and we can run it. There we see ‘Hello world’ output, similar to how it was before. Actually, before we move forward, let's get rid of this message. It is just going to keep getting in the way. Let's go to, I think that was in the SphereController script. Yes, indeed. Let's comment that out like that so we no longer see that message. We will comment it back in later, I am sure we will need it again.

What do you think happens here with this plus sign operator there, which is an operator on the two string variables, again, nouns you can think of them as, that we input in our debug log? What do you think it is doing? It is familiar, right? It is like the plus sign, of course, in math. It is kind of like that, except when we use the plus sign in mathematical operations, we are combining numbers, which doesn't make much sense when dealing with words, or in this case strings as it is referred to in coding. In this case, actually, it is referred to as the concatenation operator. In other words, it just glues strings together as was probably obvious there with the output. We will get into the math stuff pretty soon here. Mathaphobes, don't worry. It is really basic stuff. Let's stick with the stuff we have right now and take a closer look on what we wrote to understand variables as nouns and operations as verbs. First we declared and assigned two variables. Once you understand one, you will understand the other.

Let's look closer at the first one we declared. We have a string str1="Hello" and then a semi colon on the end. Remember how we spoke about containers earlier with those squiggly brackets for class and method? Well, here again we see that concept pop up in a different way. Variables themselves are sort of like a container in their own right that store stuff. We start off by declaring what kind of stuff the container stores with the prefixing with the variable type Here the prefix is string. This is necessary in C#, which is a fairly strictly-typed language. The type that we define here, that we declare here I should say, constrains what we are allowed to store in this container. If it is a cookie jar, don't think about putting jelly beans in that cookie jar, it just won't work. You can't mix type. Once you declare the type it has to store that value type.

The type we are using here is string, which simply means a sequence of characters. Then we created a user-defined name, str1, which is sort of like… It is again like the label of your variable container so you can refer to it in your instructions throughout your code. Then, after the user defined name str1, we have the equal sign which, again, looks like a familiar mathematical operator but it is actually referred to as the assignment operator. Basically it takes whatever is to the right of it and stuffs it into the variable container on the left. At the end of that value that you stuff into the container we terminate with a semi colon, which can be thought of as similar to a period written in a natural language. It just ends that sentence, so to speak. Here we have an entire sentence already in our code, statement again in coding speak. We have a noun... Well, we have a viable which is like a noun and we have an assignment operator, the equal sign, which is a lot like a verb when you are talking about a natural language. We can read this statement something like, "The string hello goes into the "string container named str1." In computing terms, this instruction tells the computer to carve out some space in memory suitable for storing string data, and then actually encode that string data with 0's and 1's physically onto the memory space. That is what this statement/instruction says. We don't have to have the assignment and the declaration of this variable container on the same line.

We can also write it simply like this, we can declare on one line just that the container exists. There is nothing in it. Then we can assign the value on another line by typing it out on its own line: str1="Hello". That essentially gets the same result, but it is useful in code often when you know that you want the variable available. You want it to be set or you want it to be available without being given a value. We just don't want to set it just yet because it has to be set elsewhere, but yet it still needs to be made available in a broader scope. That is where this is useful. Don't worry about scope right now, we will get a lot more into that, but you will see stuff like this in coding often and that is what it means usually. You may notice that the first line, string str1, doesn't really have an operation. It doesn't seem to be a full statement. It seems to kind of violate this rule of “It is kind of like a natural language where you form full statements” full sentences sort of. It is actually a full statement, somewhat uniquely so in coding. It is just equivalent of setting aside an empty labeled container. That is really all it is doing. You can treat whatever is inside the container at any given moment as the same thing as providing the literal value.

In other words, if we just wanted to write in hard-code the string “Hello” in our Debug.Log() method input argument, it is the same thing as typing in str1, right? Because str1 holds hello, it is the exact same thing. The only difference being, of course, that when you write in “Hello” in the Debug.Log() method argument, you can't then reference it later, whereas with str1 you could type in str1 as many times as you want in as many different places and it will in those different places be treated like the string “Hello” Alright. That is the string value type, right? Which is predefined in C#. Let's look at what other value types are predefined in C#. Actually, we will just focus on a few of the basic ones right now that will be common to all of our coding that we will be doing within Unity. We will have int, the type int, the type float, and the type bool.

Alright. Those are the rest of the types that are basic data value types in C# that we will be using. Let's start with the simplest type, and that is int. Int stands for integer, which is a whole number. That is, it cannot be represented as a fraction or decimal. Any number that is from 0 to 2,147,483,647. I am sorry if you wanted to represent 2,147,483,648, you can't do it with this value type. Otherwise, you are good to go for any other whole number. That includes negative values. You can do something like this. Let's first comment this out, we don't need all of this right at the moment. We can do this, we will declare the type for this variable and we'll give it a name. Just x because it is easy, has algebraic connotations. We will stuff the value 2, which is an integer so it is valid, to go into this variable container x. Output to out Debug.Log( x+x) Alright. Save that. Run it. There you go.

Here we are using the plus sign as a mathematical operator on the variable, so it does the mathematics calculation and gives back the result. Just as before, where we saw the variable can be treated as the actual value of which it stores, let's just illustrate that with doing this. Instead of typing in x, just type in 2. There you go, the same calculation, 4. 2 + 2 = 4, x +x = 4, x + 2 = 4, and so on.


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