NodePath

A pre-parsed scene tree path.

Descripción

El tipo Variant integrado NodePath representa una ruta a un nodo o propiedad en una jerarquía de nodos. Está diseñado para pasarse de manera eficiente a muchos métodos integrados (como Node.get_node(), Object.set_indexed(), Tween.tween_property(), etc.) sin una dependencia estricta del nodo o propiedad al que apuntan.

Una ruta de nodo se representa como una String compuesta por nombres de nodo separados por barras (/) y nombres de propiedad separados por dos puntos (:) (también llamados "subnombres"). De manera similar a una ruta de sistema de archivos, ".." y "." son nombres de nodo especiales. Hacen referencia al nodo superior y al nodo actual, respectivamente.

Los siguientes ejemplos son rutas relativas al nodo actual:

^"A" # Apunta al hijo directo A.
^"A/B" # Apunta al hijo B de A.
^"." # Apunta al nodo actual.
^".." # Apunta al nodo padre.
^"../C" # Apunta al nodo hermano C.
^"../.." # Apunta al nodo abuelo.

Una barra diagonal inicial significa que la ruta es absoluta y comienza desde SceneTree:

^"/root" # Apunta a la ventana raíz de SceneTree.
^"/root/Title" # Puede apuntar al nodo raíz de la escena principal llamado "Title".
^"/root/Global" # Puede apuntar a un nodo o escena cargados automáticamente llamados "Global".

A pesar de su nombre, las rutas de nodos también pueden apuntar a una propiedad:

^":position" # Apunta a la posición de este objeto.
^":position:x" # Apunta a la posición de este objeto en el eje x.
^"Camera3D:rotation:y" # Apunta a la cámara secundaria Camera3D y su rotación y.
^"/root:size:x" # Apunta a la ventana raíz y su ancho.

En algunas situaciones, es posible omitir el prefijo : inicial cuando se apunta a la propiedad de un objeto. Como ejemplo, este es el caso de Object.set_indexed() y Tween.tween_property(), ya que esos métodos llaman a get_as_property_path() en segundo plano. Sin embargo, generalmente se recomienda mantener el prefijo :.

Las rutas de nodos no pueden comprobar si son válidas y pueden apuntar a nodos o propiedades que no existen. Su significado depende completamente del contexto en el que se utilizan.

Normalmente no hay que preocuparse por el tipo NodePath, ya que las strings se convierten automáticamente al tipo cuando es necesario. Aún hay ocasiones en las que definir rutas de nodos es útil. Por ejemplo, las propiedades NodePath exportadas permiten seleccionar fácilmente cualquier nodo dentro de la escena que se está editando actualmente. También se actualizan automáticamente al mover, renombrar o eliminar nodos en el editor del árbol de escenas. Véase también @GDScript.@export_node_path.

Véase también StringName, que es un tipo similar diseñado para strings optimizadas.

Nota: En un contexto booleano, un NodePath se evaluará como false si está vacío (NodePath("")). De lo contrario, un NodePath siempre se evaluará como true.

Nota

Hay diferencias notables cuando usa esta API con C#. Véase Diferencias de la API de C# con GDScript para más información.

Tutoriales

Constructores

NodePath

NodePath()

NodePath

NodePath(from: NodePath)

NodePath

NodePath(from: String)

Métodos

NodePath

get_as_property_path() const

StringName

get_concatenated_names() const

StringName

get_concatenated_subnames() const

StringName

get_name(idx: int) const

int

get_name_count() const

StringName

get_subname(idx: int) const

int

get_subname_count() const

int

hash() const

bool

is_absolute() const

bool

is_empty() const

NodePath

slice(begin: int, end: int = 2147483647) const

Operadores

bool

operator !=(right: NodePath)

bool

operator ==(right: NodePath)


Descripciones de Constructores

NodePath NodePath() 🔗

Construye un NodePath vacío.


NodePath NodePath(from: NodePath)

Construye un NodePath como copia del NodePath dado.


NodePath NodePath(from: String)

Constructs a NodePath from a String. The created path is absolute if prefixed with a slash (see is_absolute()).

The "subnames" optionally included after the path to the target node can point to properties, and can also be nested.

The following strings can be valid node paths:

# Points to the Sprite2D node.
"Level/RigidBody2D/Sprite2D"

# Points to the Sprite2D node and its "texture" resource.
# get_node() would retrieve the Sprite2D, while get_node_and_resource()
# would retrieve both the Sprite2D node and the "texture" resource.
"Level/RigidBody2D/Sprite2D:texture"

# Points to the Sprite2D node and its "position" property.
"Level/RigidBody2D/Sprite2D:position"

# Points to the Sprite2D node and the "x" component of its "position" property.
"Level/RigidBody2D/Sprite2D:position:x"

# Points to the RigidBody2D node as an absolute path beginning from the SceneTree.
"/root/Level/RigidBody2D"

Note: In GDScript, it's also possible to convert a constant string into a node path by prefixing it with ^. ^"path/to/node" is equivalent to NodePath("path/to/node").


Descripciones de Métodos

NodePath get_as_property_path() const 🔗

Returns a copy of this node path with a colon character (:) prefixed, transforming it to a pure property path with no node names (relative to the current node).

# node_path points to the "x" property of the child node named "position".
var node_path = ^"position:x"

# property_path points to the "position" in the "x" axis of this node.
var property_path = node_path.get_as_property_path()
print(property_path) # Prints ":position:x"

StringName get_concatenated_names() const 🔗

Returns all node names concatenated with a slash character (/) as a single StringName.


StringName get_concatenated_subnames() const 🔗

Returns all property subnames concatenated with a colon character (:) as a single StringName.

var node_path = ^"Sprite2D:texture:resource_name"
print(node_path.get_concatenated_subnames()) # Prints "texture:resource_name"

StringName get_name(idx: int) const 🔗

Returns the node name indicated by idx, starting from 0. If idx is out of bounds, an error is generated. See also get_subname_count() and get_name_count().

var sprite_path = NodePath("../RigidBody2D/Sprite2D")
print(sprite_path.get_name(0)) # Prints ".."
print(sprite_path.get_name(1)) # Prints "RigidBody2D"
print(sprite_path.get_name(2)) # Prints "Sprite"

int get_name_count() const 🔗

Returns the number of node names in the path. Property subnames are not included.

For example, "../RigidBody2D/Sprite2D:texture" contains 3 node names.


StringName get_subname(idx: int) const 🔗

Returns the property name indicated by idx, starting from 0. If idx is out of bounds, an error is generated. See also get_subname_count().

var path_to_name = NodePath("Sprite2D:texture:resource_name")
print(path_to_name.get_subname(0)) # Prints "texture"
print(path_to_name.get_subname(1)) # Prints "resource_name"

int get_subname_count() const 🔗

Returns the number of property names ("subnames") in the path. Each subname in the node path is listed after a colon character (:).

For example, "Level/RigidBody2D/Sprite2D:texture:resource_name" contains 2 subnames.


int hash() const 🔗

Returns the 32-bit hash value representing the node path's contents.

Note: Node paths with equal hash values are not guaranteed to be the same, as a result of hash collisions. Node paths with different hash values are guaranteed to be different.


bool is_absolute() const 🔗

Returns true if the node path is absolute. Unlike a relative path, an absolute path is represented by a leading slash character (/) and always begins from the SceneTree. It can be used to reliably access nodes from the root node (e.g. "/root/Global" if an autoload named "Global" exists).


bool is_empty() const 🔗

Returns true if the node path has been constructed from an empty String ("").


NodePath slice(begin: int, end: int = 2147483647) const 🔗

Returns the slice of the NodePath, from begin (inclusive) to end (exclusive), as a new NodePath.

The absolute value of begin and end will be clamped to the sum of get_name_count() and get_subname_count(), so the default value for end makes it slice to the end of the NodePath by default (i.e. path.slice(1) is a shorthand for path.slice(1, path.get_name_count() + path.get_subname_count())).

If either begin or end are negative, they will be relative to the end of the NodePath (i.e. path.slice(0, -2) is a shorthand for path.slice(0, path.get_name_count() + path.get_subname_count() - 2)).


Descripciones de Operadores

bool operator !=(right: NodePath) 🔗

Devuelve true si dos rutas de nodo no son iguales.


bool operator ==(right: NodePath) 🔗

Devuelve true si dos rutas de nodo son iguales, es decir, si están compuestas por los mismos nombres de nodo y subnombres en el mismo orden.