Skip to content

🐙 HW 2: Classes & Coroutines

Assignment Deadline

Gradescope assignment due Friday, January 19th, 2024

Submit

via GIPHY

Classes

Being the king of the object-oriented world, classes are essential concepts to grasp. Classes are reference types that are null by default until you explicitly create an instance of the class by using the new operator or assign it an object of a compatible type that may have been created elseswhere. They are some of the most powerful ways to define new types by bundling data (fields) and operations on that data (methods).

Some important definitions:

  • Object: A thing in your software, responsible for a slice of the entire program. They define what information the object must remember and the capabilities it can perform when requested
  • Classes: Categorized C# objects to establish variables and methods of any object. Think of classes as a blueprint or pattern for objects that belong in a subset
  • Constructor: Helps new instances that are created by classes, to be ready for use. They are special methods that run when an object comes to life to ensure it begins life in a good state. They must use the same name as the class, and they cannot list a return type
DeclaringClasses.cs
// Declaring an object of type MyClass.
MyClass mc = new MyClass();

// Declaring another object of the same type, assigning it the value of the first object.
MyClass mc2 = mc;

// Classes are declared by using the class keyword followed by a unique identifier
// [access modifier] - [class] - [identifier]
public class Customer 
{
    // Fields, properties, methods and events go here
}

// Objects can be created using the new keyword followed by the name of the class
Customer object1 = new Customer();

Couroutines

Courtines are really powerful in Unity by how they hook into Unity's core loop by running every frame. When a coroutine, it runs like a function until it reaches a yield statment. It then sets a sort of bookmark and yields, which tells the rest of the game to proceed. Each frame right after the Update function, Unity calls the coroutine again. The coroutine returns to its bookmark and checks its yield condition. When the yield condition is true, for exa mple, when 1.5 seconds have passed, the bookmark is deleted and the rest of the coroutine function runs as usual. Coroutines are functions and you call them with the following syntax.

When to use couroutines in Unity:

  • Create repeating actions
  • To run an animation or play a sound that doesn't change the game state
1
2
3
4
5
6
7
8
9
// Coroutine basic setup
StartCoroutine(PlayFlagpoleAnimation());

IEnumerator PlayFlagpoleAnimation()
{
    // Do stuff
    yield return someCondition;
    // Do more stuff
}

Below is an example of Unity's built-in WaitForSeconds coroutine. While working in Unity, the coroutine you will use the most (by far) is Unity's built-in WaitForSeconds coroutine. The yield keyword means keep going with the rest of the game. Everything after the return is called the yield condition. It is something that will eventually be true. For example, afte 1.5 seconds have passed.

1
2
3
4
5
// Do stuff
// Then wait
yield return new WaitForSeconds(1.5f);

// Everything after the yield happens after 1.5 seconds

The coroutine function can have more than one yield statement. It works the same way; the "bookmark" just moves to the latest yield statement.

1
2
3
4
5
6
7
// Do stuff
// Then wait 1.5 seconds
yield return new WaitForSeconds(1.5f);

// Do stuff
// Then wait 2 seconds
yield return new WaitForSeconds(2.0f);

Problems

Before we get can get started with the homework problems, please clone the following repository https://github.com/debbieyuen/ctin583-hw02.git.

Step 1: Cloning with Terminal

If you are using terminal, use cd to change into the your desired directory. Then git clone https://github.com/debbieyuen/ctin583-hw02.git.

Image title

Image title

Image title

Now that you have successfully cloned the repository to your computer, it is time to create your own branch! Creating a branch will allow you to have your own version of the code to work off of without making changes to the main branch. In this way, each student will have a copy of the homework assignment to work on on their own respective branches.

Replace "debbie" with your first name. Here we create a new branch.

$ git branch debbie

Here we check-in to the branch we just created

$ git checkout debbie 

Problem 1: Player's Name

In this problem, we will practice creating and using variables in C# in the context of Unity. A variable is declared by listing its type and its name together (string username;).

A variable is assigned a value by placing the variable name on the left side of an equal sign and the new value on the right side. This new value may be an expression that the computer will evaluate to determine the value (username = Console.ReadLine();).

Retrieving the variable's current value is done by simply using the variable's name in an expression ("Hi " + username). In this case, your program will start by retrieving the current value in username. It then uses that value to produce the complete "Hi [name]" message. This combined message is what is supplied to the WriteLine method.

You can declare a variable anywhere within your code. Still, because variables must be declared before they are used, variable declarations tend to gravitate toward the top of the code.

In a C# Console App, we may define and print out our line similar to the block of code below:

1
2
3
4
5
6
// Declaring a variable
string username;
// Assigning a value to a variable
username = Console.ReadLine();
// Retrieving its current value
Console.WriteLine("My player's name is " + username);

Problem 1: Printing Variables

In PlayerController.cs, convert the above code to work in Unity and print out in Unity's console. Define a private variable for your player or character's name. Where should you define the name? What is the syntax to print to Unity's console?

Problem 2: Enemy Mov't

In your game, the player encounters enemies as well. Colliding with them will cause problems. But before we get to collisions, we need to call two existing functions

Functions are used to group a block of code. This can be useful in many ways, for example, in the lecture about operations with variables we performed addition on two variables, what if you need to do that often in your code? Functions let you write one piece of code and reuse it over and over again!

Problem 2: Calling Functions

How do we call classes and functions? Where should we call them? In EnemyCollision.cs, call the Movement() and Shoot() functions.

Problem 3: Which Weapon

Before we can use a class, we must define it or use a predefined class (Unity has many!). Many C# programmers place each class in a separate file for organization. As our programs grow in size, having all our classes in one file can become overwhelming and disorganized. For this homework assignment, we will place them in the same file.

Defining a new class is done with the class keyword, followed by the class's name, followed by a set of curly braces. Names are usually capitalized with UpperCamelCase. Inside the class's curly braces, we can place the variables and methods that the class will need to do its job.

Defining Classes

In EnemyCollision.cs define a new, public class named Weapons and define int variables to represent arrow, sword, rocket.

Problem 4: Comments

Comments are bits of text placed in your program, meant to be annotations on the code for humans -- you and other programmers. The compiler ignores comments.

Comments have a variety of uses:

  • You can add a description about how some tricky piece of code works, so you don't have to try to reverse engineer it later.
  • You can leave reminders in your code of things you still need to do. These are sometimes called TODO comments.
  • You can add documentation about how some specific thing should be used or works. Great to help others look through your code
  • You can temporarily comment out large chunks of code. A handy keyboard shortcut is Command and /.

Comments

In PlayerController.cs, describe what each line of code is doing. Start from the very top of the file at using.System.Collections;

Submission

GitHub Pull Requests

To receive credit for this homework assignment, please make sure you provide a link to your GitHub branch and name the branch as your first name. Then assign Nile and Debbie as Reviewers and Assignees before you hit the green Create Pull Request button.

Image title

Image title

Image title

Kitchen Chaos: Code Style, Naming Rules

Start watching the Kitchen Chaos tutorial from 00:20:28 Create Project. You are welcome to continue working on the project for as long as you want until the due date but for this homework, please at least watch until 00:39:30, the end of Code Styles, Naming Rules section. You do not have to submit anything on Gradescope for this section.