Class structure
- Game Development course
- Beginner
- Lesson 27/83
- 4 min
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.
Practice 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.
Starter code
using System;
public class Player
{
// health alanini tanimla
public void ShowHealth()
{
// can degerini yazdir
}
}
public class Program
{
public static void Main()
{
Player player = new Player();
player.ShowHealth();
}
}Sample 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();
}
}Expected output
Can: 100
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 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 Correct answer
- To play 3D audio in the project
- To create a new camera in the scene
Explanation: Fields are variables that hold the state data of a class or object, such as health or speed.
2 Declaring a void method
public ____ Jump()
{
}
public void Jump()
{
}
Explanation: Methods that do not return any value specify their return type as 'void'.
3 Class components
| Term | Meaning |
|---|---|
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 |