Functions are helpful for many reasons.
GDScript Functions all belong to a
Some functions are defined by the user (programmer), while others are included with the programmer language.
Now let's learn how to make our own GDScript Functions! Let's start with a simple function that does not return anything.
We will make a function that takes a person's name as a parameter, then prints a good morning message. A
Mouse Hover over the ➼ blue text in the description to highlight the code.
# Function: No Return
func print_message (name):
print ("Good Morning ", name)
➼ func - Keyword indicating a function is being declared
➼ print_message - The name I choose for my function
➼ name - The function's parameter
➼ print ("Good Morning ", name) - The code that executes when the function is called
Now let's call our function using "Frank" as our parameter.
# Function: No Return
func print_message (name):
print ("Good Morning ", name)
func _ready():
# Pass in Frank
print_message("Frank")
** Debug Process Started ** OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2) Good Morning Frank ** Debug Process Stopped **
Now let's make a function that returns something! We will make a function name
Mouse Hover over the ➼ yellow text in the description to highlight the code.
# Function: Returns the sum of its parameters
func add_nums(num1,num2):
var sum = num1 + num2
return sum
# Call add_nums with parameters 2 and 3 and store the result in my_sum
var my_sum = add_nums(2,3)
func _ready():
# print result
print (my_sum)
➼ func - Keyword indicating we are declaring a function
➼ add_nums - Name of the function
➼ num1,num2 - Function parameters
➼ function code - The code that executes when our function is called
➼ sum - A variable named sum is equal to the sum of our parameters added together
➼ return sum - The function returns the value of sum
➼ my_sum - We call the function add_nums with parameters (2,3) and set my_sum equal to the return value
➼ print (my_sum) - We print the value of my_sum
** Debug Process Started ** OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2) 5 ** Debug Process Stopped **
Next we will rewrite the healing code from our if statements lesson into a healing function.
extends Node
# Declare Arrays
var paladinSkills = [20,5,15,18,5,10]
var knightSkills = [13,15,10,5,15,10]
# Declare heal function
func heal (skillArray):
var healing = 0
var baseScore = skillArray [3] - skillArray [4]
if baseScore > 10:
healing += (baseScore / 5)
return healing
# call function passing in paladinSkills
var paladin_healing = heal(paladinSkills)
# call function passing in knightSkills
var knight_healing = heal(knightSkills)
func _ready():
# Print Results in a pretty message
print ("Paladin Heals: ", paladin_healing)
print ("Knight Heals: ", knight_healing)
** Debug Process Started ** OpenGL ES 2.0 Renderer: Mesa DRI Intel(R) UHD Graphics 620 (Kabylake GT2) Paladin Heals: 2 Knight Heals: 0 ** Debug Process Stopped **