Reader small image

You're reading from  Learning C# by Developing Games with Unity - Seventh Edition

Product typeBook
Published inNov 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781837636877
Edition7th Edition
Languages
Tools
Right arrow
Author (1)
Harrison Ferrone
Harrison Ferrone
author image
Harrison Ferrone

Harrison Ferrone is an instructional content creator for LinkedIn Learning and Pluralsight, tech editor for the Ray Wenderlich website, and used to write technical documentation on the Mixed Reality team at Microsoft. He is a graduate of the University of Colorado at Boulder and Columbia College, Chicago. After a few years as an iOS developer at small start-ups, and one Fortune 500 company, he fell into a teaching career and never looked back.
Read more about Harrison Ferrone

Right arrow

Working with Classes, Structs, and OOP

For obvious reasons, the goal of this book isn’t to give you a splitting headache from information overload. However, these next topics will take you out of the beginner’s cubicle and into the open air of object-oriented programming (OOP). Up to this point, we’ve been relying exclusively on predefined variable types that are part of the C# language: under-the-hood strings, lists, and dictionaries that are classes, which is why we can create them and use their properties through dot notation. However, relying on built-in types has one glaring weakness—the inability to deviate from the blueprints that C# has already set.

Creating your classes gives you the freedom to define and configure blueprints of your design, capturing information and driving action that is specific to your game or application. In essence, custom classes and OOP are the keys to the programming kingdom; without them, unique programs will be few...

Join our book community on Discord

https://packt.link/csharpunity22

One of the central duties of a computer is to control what happens when predetermined conditions are met. When you click on a folder, you expect it to open; when you type on the keyboard, you expect the text to mirror your keystrokes. Writing code for applications or games is no different—they both need to behave in a certain way in one state, and in another when conditions change. In programming terms, this is called control flow, which is apt because it controls the flow of how code is executed in different scenarios.

In addition to working with control statements, we'll be taking a hands-on look at collection data types. Collections are a category of types that allow multiple values, and groupings of values, to be stored in a single variable. We'll break the chapter down into the following topics:

  • Selection statements
  • Working with array, dictionary, and list collections
  • Iteration statements with...

Selection statements

The most complex programming problems can often be boiled down to sets of simple choices that a game or program evaluates and acts on. Since Visual Studio and Unity can't make those choices by themselves, writing out those decisions is up to you.

The if-else and switch selection statements allow you to specify branching paths, based on one or more conditions, and the actions you want to be taken in each case. Traditionally, these conditions include the following:

  • Detecting user input.
  • Evaluating expressions and Boolean logic.
  • Comparing variables or literal values.

You're going to start with the simplest of these conditional statements, if-else, in the following section.

The if-else statement

if-else statements are the most common way of making decisions in code. When stripped of all its syntax, the basic idea is: If my condition is met, execute this block of code; if it's not, execute this other block of code. Think of these statements as gates,...

Collections at a glance

So far, we've only needed variables to store a single value, but there are many conditions where a group of values will be required. Collection types in C# include arrays, dictionaries, and lists—each has its strengths and weaknesses, which we'll discuss in the following sections.

Arrays

Arrays are the most basic collection that C# offers. Think of them as containers for a group of values, called elements in programming terminology, each of which can be accessed or modified individually:

  • Arrays can store any type of value; all the elements need to be of the same type.
  • The length, or the number of elements an array can have, is set when it's created and can't be modified afterwards.
  • If no initial values are assigned when it's created, each element will be given a default value. Arrays storing number types default to zero, while any other type gets set to null or nothing.

Arrays are the least flexible collection type in C#. This...

Iteration statements

We've accessed individual collection elements through the subscript operator, along with collection type methods, but what do we do when we need to go through the entire collection element by element? In programming, this is called iteration, and C# provides several statement types that let us loop through (or iterate over, if you want to be technical) collection elements. Iteration statements are like methods, in that they store a block of code to be executed; however, unlike methods, they can repeatedly execute their code blocks as long as their conditions are met.

for loops

The for loop is most commonly used when a block of code needs to be executed a certain number of times before the program continues. The statement itself takes in three expressions, each with a specific function to perform before the loop executes. Since for loops keep track of the current iteration, they are best suited to arrays and lists.

Take a look at the following looping statement...

Summary

As we bring the chapter to a close, we should reflect on how much we've accomplished and what we can build with that new knowledge. We know how to use simple if-else checks and more complex switch statements, allowing decision making in code. We can create variables that hold collections of values with arrays and lists or key-value pairs with dictionaries. This allows complex and grouped data to be stored efficiently. We can even choose the right looping statement for each collection type, while carefully avoiding infinite-loop crashes.

If you're feeling overloaded, that's perfectly OK—logical, sequential thinking is all part of exercising your programming brain.

The next chapter will complete the basics of C# programming with a look at classes, structs, and object-oriented programming (OOP). We'll be putting everything we've learned so far into these topics, preparing for our first real dive into understanding and controlling objects in the Unity...

Join us on Discord!

Read and discuss this book with other users, Unity/C# experts, and the author. Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more.

Join now!

https://packt.link/csharpunity2021

Summary

Our journey into classes, structs, and OOP marks the end of the first section on the fundamentals of C#. You’ve learned how to declare your classes and structs, which is the scaffolding for every application or game you’ll ever make. You’ve also identified the differences in how these two objects are passed and accessed and how they relate to OOP. Finally, you got hands-on with the tenets of OOP—creating classes using inheritance, composition, and polymorphism.

Identifying related data and actions, creating blueprints to give them shape, and using instances to build interactions are strong foundations for approaching any program or game. Add the ability to access components to the mix, and you’ve got the makings of a Unity developer.

The next chapter will segue into the basics of game development and scripting object behavior directly in Unity. We’ll start by fleshing out the requirements of a simple open-world adventure game...

Pop quiz—all things OOP

  1. What method handles the initialization logic inside a class?
  2. Being value types, how are structs passed?
  3. What are the three main tenets of OOP?
  4. Which GameObject class method would you use to find a component on the same object as the calling class?

Don’t forget to check your answers against mine in the Pop Quiz Answers appendix to see how you did!

Join us on discord!

Read this book alongside other users, Unity game development experts and the author himself.

Ask questions, provide solutions to other readers, chat with the author via. Ask Me Anything sessions and much more.

Scan the QR code or visit the link to join the community.

https://packt.link/csharpwithunity

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning C# by Developing Games with Unity - Seventh Edition
Published in: Nov 2022Publisher: PacktISBN-13: 9781837636877
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Harrison Ferrone

Harrison Ferrone is an instructional content creator for LinkedIn Learning and Pluralsight, tech editor for the Ray Wenderlich website, and used to write technical documentation on the Mixed Reality team at Microsoft. He is a graduate of the University of Colorado at Boulder and Columbia College, Chicago. After a few years as an iOS developer at small start-ups, and one Fortune 500 company, he fell into a teaching career and never looked back.
Read more about Harrison Ferrone