See all glossary terms

Function

A function is like a mini-machine you can use to do specific tasks in your code. Functions let you group multiple lines of code together under a name, so you can easily execute those lines whenever you need. It makes your code easier to reuse.
Say you're making a game where the player can shoot a projectile (for example, a fireball or a bullet).
In Godot, firing a projectile involves several steps. You may need to:
  1. Load the projectile scene.
  2. Create an instance of the projectile.
  3. Set its position to where you want it to spawn.
  4. Give it a speed.
  5. Add the projectile instance to the game so it appears on the screen.
And perhaps more. You might also want to play a sound effect or show an animation when the player shoots.
You can group all these steps into a single function called shoot(). Then, whenever you want the player to shoot, you can call the function like this: shoot()! This makes the code easy to reuse.
The function might look like this:
func shoot():
    var loaded_scene := preload("fireball.tscn")
    var projectile := loaded_scene.instantiate()
    projectile.position = get_node("Cannon").global_position
    projectile.speed = 1000.0
    add_child(projectile)

Functions can have parameters

Functions can have optional inputs called parameters. These parameters allow us to customize how the function works each time we call it.
Take the shoot() function above. It's hard-coded to always spawn a fireball. What if you want to spawn different spell projectiles, like a healing bubble, a rock, or a crystal shard? You'd have to create a new function for each type of projectile.
If all projectiles work the same way, you can make the function more flexible by adding a parameter.
Here's how the function might look with one parameter to change the spawned projectile:
func shoot(projectile_scene: PackedScene) -> void:
    var projectile := projectile_scene.instantiate()
    projectile.position = get_node("Cannon").global_position
    projectile.speed = 1000.0
    add_child(projectile)
Now, you can call the function like this to shoot a healing bubble, a rock, or a crystal shard:
shoot(preload("healing_bubble.tscn"))
shoot(preload("rock.tscn"))
shoot(preload("crystal_shard.tscn"))
Parameters make functions more flexible and powerful. You can create a single function that works in different situations by giving it different inputs.
Note that:
  • You can have multiple parameters or none at all.
  • You can give default values to parameters to make some parameters optional.

See Also

Related terms in the Glossary