See all glossary terms

Virtual Function

Godot provides some functions that are empty and do nothing by default. They exist only to override them them, and they don't do anything otherwise. We call these virtual functions.
For example, the _ready() and _process() functions are virtual. They are defined in the engine and don't do anything by default.
Virtual functions allow Godot to assume that every node has these functions, and the engine can call them without checking if they exist. If a node doesn't have a script in your project, internally, Godot will still call these functions blindly, and nothing will happen. If the node has a script that overrides these functions, your code will run.
Some of the most used virtual functions are:
  • _ready(): Called when the node is added to the scene tree.
  • _process(delta): Called every frame.
  • _physics_process(delta): Called every physics frame. Physics runs at a fixed frame rate to ensure consistency in the simulation.
  • _input(event): Called for every input event.
  • _unhandled_input(event): Called for every input event not consumed by _input().
  • _enter_tree(): Called when the node enters the scene tree, before _ready().

Virtual functions in GDScript

GDScript doesn't exactly have virtual functions, but you can create your own virtual functions by creating empty functions that you expect to be overridden. For example, here's a class named Unit with a virtual function take_damage():
class_name Unit

var health := 10

func take_damage(_amount: int) -> void:
    pass
In a class that extends the Unit class, you can override the take_damage() function to make it do something. Here, it reduces the health of the unit by the given amount and ensures the health doesn't go below zero:
class_name Player extends Unit

func take_damage(amount: int) -> void:
    health = max(0, health - amount)

See Also

Related terms in the Glossary