0% found this document useful (0 votes)
11 views14 pages

4.1 Game Coding Foundation - 26.07.2023

Module 4 covers game coding fundamentals, focusing on C# basics, Unity-specific concepts, APIs, and scripting best practices. Students will learn key coding skills for game mechanics, debugging, and level design to aid their capstone project. The module includes practical tutorials and emphasizes the importance of documentation and consistent coding practices.

Uploaded by

midare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views14 pages

4.1 Game Coding Foundation - 26.07.2023

Module 4 covers game coding fundamentals, focusing on C# basics, Unity-specific concepts, APIs, and scripting best practices. Students will learn key coding skills for game mechanics, debugging, and level design to aid their capstone project. The module includes practical tutorials and emphasizes the importance of documentation and consistent coding practices.

Uploaded by

midare
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Game coding foundation

Module 4: 4.1 Game coding fundamentals

In this section, we will cover:


1. C# Basics
2. Unity-specific concepts
3. Unity APIs and scripting
4. Scripting best practices
5. Practical tutorial guide

Lesson summary
This lesson will give students an overview of game coding fundamentals and develop key coding
skills that can be used in the capstone project.

At the end of this lesson, students should be able to:

• Explore coding techniques for implementing different types of game mechanics, expanding
their coding skills
• Understand the importance of progressive game testing and debugging, ensuring the game
functions as intended and addressing any issues that arise
• Develop skills in basic level design layout and planning, ensuring a solid foundation for
game development.

Related learning activities / Practical skills


Increase your understanding and contribute to the capstone project by completing the learning
activities:

- Interactive content: Need help? Assistance discussion board


1. C# Basics
Developed by Microsoft, C# is a powerful, object-orientated programming language that is widely
used in software development, including games developed in Unity. It offers a rich set of features
for creating robust and efficient applications.

Main C# concepts:
• Class
• Variables and data types
• Operators Visual Studio is the coding program that pairs

• Conditional statements with Unity to write C#.

• Functions.

Class
A class is a fundamental building block that encapsulates data and behaviour. Classes define the
structure, properties and methods that objects of that class will have. In Unity, classes are
extensively used to create and manage game objects, components and game logic.

Encapsulates is a principle of OOP, it enables the bundling of data and methods within a single
unit called a class. You will use class’s extensively in Unity to make script classes specific to a
game object. We will learn more about this later.

public class PlayerController : MonoBehaviour


{
// Start is called before the first frame update
void Start()
{

// Update is called once per frame


void Update()
{

}
}

Module 4
4.1 Game coding foundation
Page 2 of 14
CRICOS provider number: 00122A | RTO Code: 3046
Variables
Variables are used to store and manipulate data in C#. Variables can hold a variety of data, hence
they need to have specific data types assigned to them when they are created.

Variables can hold numbers (integers or floats), strings (words), or true or false choices
(Booleans).

int int currentIndex;

Represents integers (whole numbers) without decimal points, such as 1, 2, -5, etc. It is suitable for
most counting and indexing operations.

float float score;

Represents floating-point numbers with decimal places, such as 3.14, -0.5, etc. Floats are used for
operations requiring precision but with a wider range of values compared to integers.

string string DrinkOrder:

Represents a sequence of characters, such as "Hello", "Unity", etc. Strings are commonly used for
handling textual data.

bool bool isAllowed;

Represents a Boolean value, either true or false. Booleans are used for conditions, logical
operations and making decisions in your code.

Array string DrinksOrder[“Water”, “Apple Juice”, “Lemonade””];

Arrays
Arrays and lists are used for storing and manipulating multiple values in C#. Arrays are fixed-size
collections of elements of the same type. They allow you to store multiple values in a single
variable.

Module 4
4.1 Game coding foundation
Page 3 of 14
CRICOS provider number: 00122A | RTO Code: 3046
Operators
Operators in C# allow you to perform various operations on variables and values. Operators
enable you to perform calculations, make comparisons and control program flow.

They include:
• arithmetic operators (+, -, *, /)
• comparison operators (==, !=, <, >)
• logical operators (&&, ||, !)
• assignment operators (=, +=, -=) and more.

float lives = 3
DrinksOrder == “Water”
!isAllowed
float score += 1;

Conditional statements
Conditional statements allow you to control the flow of your program based on certain conditions.
The most commonly used conditional statements in C# are the if-else statement and the switch
statement.

The if-else statement checks a condition and executes different blocks of code based on whether
the condition is true or false.

if(lives == 0){
// then end the game
gameEnd();
}

Module 4
4.1 Game coding foundation
Page 4 of 14
CRICOS provider number: 00122A | RTO Code: 3046
The switch statement provides multiple cases and executes the block of code associated with the
matching case.

switch (object){

case “collectible”:
score += 1;
break;

case “enemy”:
lives -= 1;
break;

Loops
Loops are used to execute a block of code repeatedly. C# offers several loop structures:

The for loop repeats a block of code a specific number of times, based on a defined initialisation,
condition and iteration.

for (int i = 1; i <= 5; i++)


{
// repeat this command until i becomes greater than or = to 5
}

Module 4
4.1 Game coding foundation
Page 5 of 14
CRICOS provider number: 00122A | RTO Code: 3046
The while loop repeats a block of code as long as a specific condition remains true. The do-while
loop is similar to the while loop but executes the block of code at least once before checking the
condition.

while (isAllowed)
{
// Code do this command for as long as it is true
}

Functions/Methods
Functions (also called methods) in C# allow you to encapsulate reusable blocks of code. They
accept input parameters, perform specific operations and return values (if needed). Functions
enable modular programming, code reusability and improved organisation of your codebase.

void CheckLives(){

// check to see if all lives are gone

Module 4
4.1 Game coding foundation
Page 6 of 14
CRICOS provider number: 00122A | RTO Code: 3046
Event handlers
In Unity, an event handler is a function or method that is registered to respond to a specific event
or action that occurs within the game. It allows you to define custom behaviour that should execute
when a particular event is triggered.

Unity provides a variety of built-in events that you can subscribe to and handle using event
handlers.

These events cover different aspects of the game, such as input, collisions, animations and UI
interactions.

private void OnCollisionEnter2D(Collision2D collision)


{
// add in commands for when we hit a specific items
}

private void OnCollisionExit2D(Collision2D collision)


{

// add in commands for move away from a specific item


}

Module 4
4.1 Game coding foundation
Page 7 of 14
CRICOS provider number: 00122A | RTO Code: 3046
2. Unity-specific concepts

Scenes
In Unity, we use “scenes” as the building blocks of your game. A scene can represent specific
levels, menus or environments. In the Unity Editor, you can create, modify and organise scenes,
allowing you to structure and control the flow of your game.

In this image, you can see several scenes have been created and organised in the “assets” folder.

GameObjects
GameObjects make up the objects in your game, they will be the base for characters, objects and
environments. A GameObject serves as a containers that hold components and define the
properties, behaviours and relationships of the objects in your scene.

Types of GameObjects include: 3D, 2D, etc.

Module 4
4.1 Game coding foundation
Page 8 of 14
CRICOS provider number: 00122A | RTO Code: 3046
In this example, the player is a 2D game object that has been placed in the hierarchy of the scene,
with multiple components attached.

Components
Components are modular pieces of functionality that you attach to GameObjects. They provide
specific behaviours or features to the GameObject they are attached to.

Examples of components include renderers, colliders, scripts, audio sources and more. By
attaching different combinations of components to a GameObject, you can create complex and
interactive game objects.

This player has SpriteRender, BoxCollider2D, RigidBody2D, PlayerMovement and Animator


components attached to it.

Module 4
4.1 Game coding foundation
Page 9 of 14
CRICOS provider number: 00122A | RTO Code: 3046
Manipulating GameObjects using C# code
In Unity, you can manipulate GameObjects programmatically using C# code. By obtaining references to
GameObjects through code, you can perform operations like moving objects, activating or deactivating
them, changing their appearance or interacting with other game elements.

// create a variable to hold the component you want to access


GameObject Player;
Animator Player_ani;
Collider2D Player_coll;
RigidBody2D Player_rg;

// to access you need to GET the component

ThePlayer.GetComponent<Animator>();

// Access the animator and tell it when to play

ThePlayer.enabled = false;

Unity-specific functions (Start(), Update(), FixedUpdate())


When you create a script in Unity, you create a class that has set of special functions already pre-
loaded into the script.

• Start(): This function is called once when a script is first enabled or when a GameObject is
instantiated. It is often used for initialisation tasks.
• Update(): The update() function is called every frame of the game. It is commonly used for
updating game logic, handling user input and performing continuous actions.
• FixedUpdate(): The FixedUpdate() function is called at a fixed rate, typically used for physics-
related calculations. It is ideal for applying forces, updating rigid body physics or performing
other actions that require deterministic behaviour.

// Start is called before the first frame update


void Start()
{

Module 4
4.1 Game coding foundation
Page 10 of 14
CRICOS provider number: 00122A | RTO Code: 3046
// Update is called once per frame
void Update()
{

3. Unity APIs and scripting


1. APIs (Application Programming Interfaces):
API stands for Application Programming Interface. It is a set of rules and protocols that allow
different software applications to communicate with each other. In the context of Unity, APIs
provide a way to access and interact with the various features and functionalities offered by the
Unity game engine.

Unity provides a vast collection of APIs that have functionality for game development, including
input handling, physics simulations, audio playback, UI (user interface) manipulation, asset
management, networking and much more.

These APIs allow developers to leverage Unity's capabilities and create customised game logic
and behaviors.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using UnityEngine.SceneManagement;

Module 4
4.1 Game coding foundation
Page 11 of 14
CRICOS provider number: 00122A | RTO Code: 3046
You can dig deeper into the APIs in your Project Settings (Edit > Project Settings)

2. Importance of documentation and online resources:


Unity provides comprehensive and up-to-date documentation that explains each API's purpose,
usage and related concepts.

Documentation helps developers quickly learn and reference the APIs, enabling them to implement
desired features and functionalities efficiently.

– https://docs.unity.com/
– https://docs.unity3d.com/ScriptReference/
– https://learn.unity.com/

Module 4
4.1 Game coding foundation
Page 12 of 14
CRICOS provider number: 00122A | RTO Code: 3046
4. Scripting best practices
Be consistent in naming
All naming is case sensitive. Ensure you spell things the same way, that you are case sensitive,
that you are following naming conventions and that you are not using an existing namespace (that
is something that already exists (for example, “Start” is already used by Unity).

Is it in the syntax?
Check the syntax of the class, variable, methods, function, condition, etc. that you have created.
Get a strong understanding of how the { } are used, and when to use a ; and when to not.

Read the error message


The console panel in Unity is your friend. (Window > General > Console) Read the message –it will
inform you of what the issue is.

Use a debugger
Many scripting programs have inbuilt de-buggers that will show you a possible solution.

Isolate the issue


What part of the code is not triggering? Is there a squiggly red line under anything in the editor?
Start there.

Test your code consistently


Test your code line by line or section by section. As you add a line, go and test it. This way you will
be able to catch any issues before you are faced with a large block of code and unsure where the
error started.

Module 4
4.1 Game coding foundation
Page 13 of 14
CRICOS provider number: 00122A | RTO Code: 3046
Interactive activity: Need help? Assistance
discussion board

This has been developed as interactive content within


your course. Please head to your course site to
complete the activity.

5. Practical tutorial guide


Please head to your course site to watch practical tutorials on game coding.

Module 4
4.1 Game coding foundation
Page 14 of 14
CRICOS provider number: 00122A | RTO Code: 3046

You might also like