Lesson 7 - Game Loop Primer

Tutorial Series: Introduction to Unity with C# Series

Previous Article  |  Next Article


In that last video, we touched a bit upon how that code we wrote in the update method worked. In this video, we will better understand how the update method within the script component attached to the game object actually drive changes that we see in that game object. We will also try to bet a better general concept of what it means to say changes are occurring on the screen. Once again, everything here is a primer in order to get you ready to understand how all the code we will be writing in the coming videos will be interpreted within Unity and our game world. If a lot of it doesn't make sense, it is supposed to not make total sense at this point. Not yet. Stay with me and try to glean as much information as you can. I think it will be helpful going forward, but we will revisit these concepts over and over again as we move forward.

First off, it is important to understand that every game, regardless of if it looks static, or if it looks like a lot of things are moving, create the illusion of motion by rapidly drawing on your screen individual discrete frames, one after the other. Each frame may or may not have some things change, but regardless whether or not there are changes, the screen is always constantly being updated or redrawn. If there are changes, those changes happen quick enough that it fools your brain into thinking there is a moving and dynamically changing world. I purposely emphasized the word 'update' or 'updated' because, surprise, this is primarily handled by the update method in Unity that we have been putting most of our code into thus far. The update method runs over and over again. It runs exactly once per frame. A common target frame rate for games is roughly 60 frames per second. If our game runs at a steady 60 frames per second, that means our update method would have run like a loop 60 times within that second. That is important. It is a very key concept, because most of the code we will be writing will be in the update method.

Try to visualize and think about that as much as you can going forward. Each single frame is rendered by a single run-through of the previous update method. If there are changes to the scene on any of these frames, the stitching of these frames together is what creates the illusion of motion. Make no mistake, each frame is completely static and stationary. Can you think of anything that sounds like that in your experience? Think about it. That is right, movies or actually any video footage for that matter. All video is just a series of frames, one after the other, comprised of still images, that when run fast enough, produces that very same illusion of motion.

To illustrate this effect and relate it to how updates work in a game world, I am going to recreate a famous scene from a movie starring Johnny Depp. I think you all know the movie, it is called Parrots of the Carby Beans. I may have said that kind of quick, but I think you probably heard that right. Anyways, the resolution is not that great in this video, so you may not be able to tell, but you can trust me, that is definitely Johnny Depp right there. Here is a famous scene from Johnny Depp in the movie where he dramatically confronts this old man eyeing his treasure chest. You can see that treasure chest right behind Johnny Depp right there. You see, it looks like Johnny is moving on a skateboard from the left over to the right, but when we take each still frame, you will see that it is just a bunch of still shots stitched together.

You may wonder what is making Johnny Depp, the real world Johnny Depp, not my recreation of him, but the real Johnny Depp, move. How does Johnny Depp as an object move before the result is captured on the next frame of the camera reel? Of course, Johnny Depp is making Johnny Depp move, right? Somewhat magically here on a skateboard, it seems an odd directorial choice, I have to say, but that is what the director chose, so I am going along with it. How does that actually happen? How does that motion happen in general? Nobody really knows entirely how that happens, but suffice to say it starts somewhere in the brain.

You can imagine that Johnny's brain is running something like an update loop. Stay with me here, I think it is going to be illustrated, and that update loop in Johnny's brain is making calculations and sending out information to his body to change his state, for him to move this way or that way. These calculations in the real Johnny Depp's brain, happen much faster than 60 discrete intervals per second. I am sure Johnny Depp is a reasonably intelligent guy, so that is why I say that, but let's for the sake of simplicity say it runs at the same rate as the capture device. Johnny Depp's brain loop, as it were, is running at 60 frames per second. 60 times per second or every 1/60 of a second.

Let's look at what that would look like frame by frame, slowed way down. There is Johnny Depp, he is an object with a brain script running this sort of update loop, which may or may not change his state incrementally every 1/60 of a second. The result of that state change or not, is captured and sent off to display as a picture of a single frame for you to see at the same rate of one frame every 1/60 of a second. We are slowing this way down so you can see what's happening in Johnny Depp's brain update before it passes it off, the result of it, off to the movie frame. You see the update loop is running, but we haven't seen a state change yet. Alright, there we go, something made Johnny Depp move in that script. He is going to budge a bit on the next frame. It is by accumulating these changes over successive frames, that we get a dramatic scene to play out, such as the famous scene from Parrots of the Carby Beans.

My apologies to Johnny Depp there, I think he can take it. Frankly, I don't think he is going to be watching this video. If he does, I think he will find a way to console himself, but I took a few liberties there with Johnny Depp. I like him, I think he is a fine actor, but anyway, I was using him to illustrate this point that hopefully was made somewhat. In case it wasn't clear, the analogy here is that Johnny Depp is your game object, while his brain running the update loop, changing the state of the Johnny Depp object in memory, in this case, is the attached script with the update method.

The camera capturing the results and displaying them onto visible frames, is something like your graphics card and screen monitor. Abstract analogies are all well and good, but let's try to bring this back to Unity and using Unity's visuals to better understand here what is happening in Unity, using a similar visual description. I made another illustration here, bear with me in my illustrations, I hope they help. On the left, we have a visual that shows the code in the update method, executing in slow motion. You see each line is being examined by the computer, one line is being read one at a time, and the update method is run full once, and is ready to hand off the results of what happened to the computer to draw on the next frame. This all happens in 1/60 of a second, if it is 60 frames per second again, very very quickly. We are slowing it way down. On the right we see the results of the changes of this update method, whether or not there were changes on the previous run-through of the update loop. Something may or may not have changed in that run-through of the update method, but nonetheless it is going to be drawn to the next frame.

On we move, onto the very next frame. The update method starts again from the top, and works its way down. Remember, it is going in a loop. Now we would see a change. An input has been read, on those lines of code, and the object moves by the amount specified. A very small amount. That is drawn on the very next frame. This hopefully all makes sense to you, but you may still be wondering, how does the update method communicate with the game object? How does this update method in the script actually send messages to, in this case in our game, the cube game object for example? In the way that Johnny Depp's brain sends messages for him to gradually change his state over time. When we look at our game object here in the inspector, remember it has components attached here to the right. These components become the properties of this object's instance. This particular game object has these properties, a transform, a cube mesh filter, box collider, mesh renderer, and the script. In code we can access many of these properties with their default names.

For example, the transform component can be accessed as a property in the code just by typing in ‘transform.’ We are going to type here, just to show, anywhere in the code, it doesn't matter, 'transform'. That property relates exactly to the game object of which this script that I am writing 'transform' in, is attached to. From there, by hitting the dot accessor, period in other words, you can access constituent properties such as the position, right, we all looked at that. We are quite familiar with that by now. We also have rotation, and so on. Position, rotation, we have scale as well. That is how we are able to write code and access those transform properties of our game object. If this script wasn't attached to this game object, typing in 'transform' would have no meaning. That is the special relationship between scripts being attached to game objects have.

A lot of concepts in this video, really concept-heavy. I totally understand that, but I think it will help you see what is happening as we move forward. Hopefully, this will give you a clear sense on how the parts relate. All I want for you is to get comfortable with the idea of how the update method in your script connects to your game object and changes its state to be rendered on the next frame displayed on the screen. That is the most important takeaway and key concept.

Again, don't get too fixated on any one thing at this stage. If you kind of understood what was being discussed in this video, feel free to think about it, rewind the tape, as it were, or just let it go and know that you will be coming back to this idea over and over again. Don't sweat it, and we will get right back to coding in the next video. 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


Please login or register to add a comment