What is a Function?
A function is a block of code that performs a specific task. Instead of repeating the same code multiple times, you can create a function and reuse it. In Unity, you can create functions for player attacks, enemy defeats, item collection, etc.
Creating a Function
public class Player : MonoBehaviour
{
void AttackEnemy()
{
Debug.Log("Attacking enemy!");
DealDamage(10);
PlayAttackSound();
UpdateCombatUI();
}
void DealDamage(int damage) { }
void PlayAttackSound() { }
void UpdateCombatUI() { }
}
- Components
void: means this function doesn't return a value (only performs actions)AttackEnemy: function name (use clear names that describe the action){ }: contains the code to execute
Calling a Function
public class Player : MonoBehaviour
{
void Update()
{
// Attack when left mouse button is pressed
if (Input.GetMouseButtonDown(0))
{
AttackEnemy(); // Execute function
}
// Jump when spacebar is pressed
if (Input.GetKeyDown(KeyCode.Space))
{
Jump(); // Execute different function
}
}
void AttackEnemy()
{
Debug.Log("Attacking enemy!");
// Attack logic...
}
void Jump()
{
Debug.Log("Jump!");
// Jump logic...
}
}
- Advantages
- No need to write the same code multiple times (reuse attack logic in multiple places)
- Modify in one place when needed (change attack method by modifying one function)
- Code is clean and easy to read (
AttackEnemy()clearly shows what it does) - Easy to fix bugs (fix in one place applies everywhere)
Why Use Functions?
Without functions (inefficient):
void Update()
{
if (Input.GetMouseButtonDown(0))
{
// Repeat attack logic every time
Debug.Log("Attacking enemy!");
DealDamage(10);
PlayAttackSound();
UpdateCombatUI();
// Write the same code again in another place
Debug.Log("Attacking enemy!");
DealDamage(10);
PlayAttackSound();
UpdateCombatUI();
}
}
With functions (efficient):
void Update()
{
if (Input.GetMouseButtonDown(0))
{
AttackEnemy(); // Simply call function
}
if (Input.GetKeyDown(KeyCode.Q))
{
AttackEnemy(); // Reuse same function
}
}
void AttackEnemy()
{
Debug.Log("Attacking enemy!");
DealDamage(10);
PlayAttackSound();
UpdateCombatUI();
}
Actual benefits in game development:
- When changing attack logic, modify only the
AttackEnemy()function and it applies everywhere - Code is easier to read so other developers can understand it easily
- Easy to fix bugs (fix in one place solves it everywhere)
- Easy to test (test just one function)