Variables are great for storing stuff, but what if you want your character to jump, attack, or shout “pew pew” when clicked?
That’s where methods come in.
Methods (also called functions) are reusable blocks of code that do something. You define them once, and call them whenever you want.
🧠 What is a Method?
Think of a method like a recipe: you write the steps once, then use them as needed.
Here’s the simplest method:
void Jump()
{
Debug.Log("The player jumped!");
}
void
means it doesn’t return anything — it just performs an action.
✋ Calling a Method
A method doesn’t run on its own. You have to call it — like this:
void Start()
{
Jump(); // Calls the Jump method when the game starts
}
When you hit play, Unity runs Start()
→ which runs Jump()
→ which prints to the Console.
🎯 Adding Parameters
A parameter is info you pass into a method. It lets you make your method more flexible.
void TakeDamage(int amount)
{
Debug.Log("Player lost " + amount + " HP");
}
You can call it like this:
TakeDamage(20); // Outputs: Player lost 20 HP
Now you’ve got a method that works with any damage value.
🔁 Bonus: Return Values
Sometimes, you want a method to give something back:
int GetScoreBonus()
{
return 100;
}
You can use it like this:
int bonus = GetScoreBonus();
Debug.Log("You got a bonus of " + bonus);
💡 The method’s type (
int
) tells you what kind of value it gives back.
🧪 Example in Unity
Here’s a Unity-friendly script using methods + parameters:
using UnityEngine;
public class PlayerActions : MonoBehaviour
{
public int health = 100;
void Start()
{
TakeDamage(30);
Heal(15);
}
void TakeDamage(int damage)
{
health -= damage;
Debug.Log("Ouch! Health is now " + health);
}
void Heal(int amount)
{
health += amount;
Debug.Log("Feeling better! Health is now " + health);
}
}
Attach this to any GameObject and hit Play — watch your health change in the Console.
🧠 Recap
- Methods are reusable code blocks that perform actions
- You can call methods inside
Start()
,Update()
, or from other methods - Parameters make your methods flexible
- Return values let methods give something back
- This is how we make stuff happen in our games
🧪 Mini Challenge: Your First Method System
- Create a new script called
EnemyAttack.cs
- Add a method called
AttackPlayer
that logs"Enemy attacks the player!"
- Add another method called
Roar
that takes astring
parameter and prints it - Call both methods in
Start()
with custom values
Test it by attaching it to a GameObject and hitting Play!
🚀 What’s Next?
Now let’s take a turn into decision-making — how your game chooses what to do, when to do it, and whether to say “you win” or “you died.”
➡️ Go to Lesson 9 → Conditional Statements (if, else)