Game Development
Class structure
Learn the C# class structure and how to define fields and methods.
The class and field Concept
In C#, blueprints that define the properties and structure of objects are called classes (class). Variables that store data inside a class are called fields (field). In Unity, when you declare a field as public, it becomes directly editable in the Inspector window.
public class Player
{
public int health = 100;
public float speed = 5.5f;
}
Fields hold the current state of an object in memory (such as health, speed, level).
Methods
Methods (method) are code blocks that encapsulate the actions and calculations a class can perform. Methods can take parameters and return a result value. If a method does not return any value, the void keyword is used as its return type.
public class Player
{
public void TakeDamage(int damage)
{
// Damage receiving code
}
}
When called, methods process parameters inside the parentheses and execute the statements in their body sequentially.
Exercise Create class field and method
Inside the Player class, add a public int health field initialized to 100. Inside the ShowHealth method, print "Can: " + health using Console.WriteLine.
Show example solution
using System;
public class Player
{
public int health = 100;
public void ShowHealth()
{
Console.WriteLine("Can: " + health);
}
}
public class Program
{
public static void Main()
{
Player player = new Player();
player.ShowHealth();
}
}
Test yourself
-
What is the primary role of fields inside a C# class?
- To change the language of the Unity editor
- To store data and state information of the object
- To play 3D audio in the project
- To create a new camera in the scene
Show answer
To store data and state information of the object — Fields are variables that hold the state data of a class or object, such as health or speed.
-
Declaring a void method
public ____ Jump()
{
}
Show answer
public void Jump()
{
}
-
Class components
- class
- Keyword that defines object templates
- field
- Variable that stores data inside a class
- method
- Executable code block performing actions
- void
- Return type for methods with no value
Next lesson: Variables and types