Up to date
This page is up to date for Godot 4.1
.
If you still find outdated information, please open an issue.
Godot interfaces¶
Often one needs scripts that rely on other objects for features. There are 2 parts to this process:
Acquiring a reference to the object that presumably has the features.
Accessing the data or logic from the object.
The rest of this tutorial outlines the various ways of doing all this.
Acquiring object references¶
For all Objects, the most basic way of referencing them is to get a reference to an existing object from another acquired instance.
var obj = node.object # Property access.
var obj = node.get_object() # Method access.
GodotObject obj = node.Object; // Property access.
GodotObject obj = node.GetObject(); // Method access.
The same principle applies for RefCounted objects. While users often access Node and Resource this way, alternative measures are available.
Instead of property or method access, one can get Resources by load access.
# If you need an "export const var" (which doesn't exist), use a conditional
# setter for a tool script that checks if it's executing in the editor.
# The `@tool` annotation must be placed at the top of the script.
@tool
# Load resource during scene load.
var preres = preload(path)
# Load resource when program reaches statement.
var res = load(path)
# Note that users load scenes and scripts, by convention, with PascalCase
# names (like typenames), often into constants.
const MyScene = preload("my_scene.tscn") # Static load
const MyScript = preload("my_script.gd")
# This type's value varies, i.e. it is a variable, so it uses snake_case.
@export var script_type: Script
# Must configure from the editor, defaults to null.
@export var const_script: Script:
set(value):
if Engine.is_editor_hint():
const_script = value
# Warn users if the value hasn't been set.
func _get_configuration_warnings():
if not const_script:
return ["Must initialize property 'const_script'."]
return []
// Tool script added for the sake of the "const [Export]" example.
[Tool]
public MyType
{
// Property initializations load during Script instancing, i.e. .new().
// No "preload" loads during scene load exists in C#.
// Initialize with a value. Editable at runtime.
public Script MyScript = GD.Load<Script>("MyScript.cs");
// Initialize with same value. Value cannot be changed.
public readonly Script MyConstScript = GD.Load<Script>("MyScript.cs");
// Like 'readonly' due to inaccessible setter.
// But, value can be set during constructor, i.e. MyType().
public Script Library { get; } = GD.Load<Script>("res://addons/plugin/library.gd");
// If need a "const [Export]" (which doesn't exist), use a
// conditional setter for a tool script that checks if it's executing
// in the editor.
private PackedScene _enemyScn