Function definition
- Game Development course
- Beginner
- Lesson 69/83
- 4 min
Learn to define functions with func.
Function definition and func
In GDScript, functions are defined using the func keyword. After the function name, parameter parentheses and a terminating colon : are placed; the body is indented.
func jump():
print("Character jumped!")
func take_damage(amount):
print("Damage taken!")Functions break repetitive code routines into modular, reusable building blocks.
Parameters and return usage
Functions can accept input parameters and send calculated results back to the caller using the return statement.
func get_welcome_message(player_name):
return "Welcome, " + player_name
func _ready():
var msg = get_welcome_message("Warrior")
print(msg)Returned values can be leveraged directly in subsequent calculations or UI label displays.
Practice Generate greeting text with function
Write a function named greet(hero_name) that returns "Hello, " + hero_name. In _ready, call this function with "Hero" and print the returned value with print.
Starter code
extends Node
# greet fonksiyonunu tanimla
func _ready():
# greet fonksiyonunu cagirip sonucu yazdir
passSample solution
extends Node
func greet(hero_name):
return "Hello, " + hero_name
func _ready():
var message = greet("Hero")
print(message)Expected output
Hello, Hero
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which keyword is used to declare a new function in GDScript?
- void
- func Correct answer
- function
- def
Explanation: In GDScript, function definitions are invariably declared using the 'func' keyword.
2 Complete function header
____ add_score(points):
func add_score(points):
Explanation: In GDScript, 'func' is written to define a function.
3 Function components
| Term | Meaning |
|---|---|
func |
Keyword to declare a function |
parameters |
Input arguments passed to a function |
return |
Command returning result to caller |
: (Colon) |
Colon starting the function body |