Referencing Nodes from your Scene

    You will find yourself referencing nodes from a scene in your code. In GDScript, that is usually achieved by using the dollar sign and the name of the object you want to reference.

    BindingNodes.md

    With SwiftGodot, you can achieve the same behavior by using the SceneTreeMacro macro (or if you are not using Macros, the BindNode property wrapper. The macro can produce a nil value if the node is not found, which forces you to check if it succeeded, and will produce more resilient code as you modify your scenes.

    SceneTree

    You typically use the path parameter to specify the path to the node in your scene that you want to reference:

    @Godot
    class Main: Node {
        @SceneTree(path: "CharacterBody2D") var player: PlayerController?
        @SceneTree(path: "locations/spawnpoint") var spawnpoint: Node2D?
        @SceneTree(path: "Telepoint") var teleportArea: Area2D?
    }

    BindNode

    BindNode is an older version, but is not as convenient as using the SceneTree macro.

    In your class declaration, use the BindNode property wrapper like this to reference the nodes that you created with the Godot Editor:

    @Godot
    class Main: Node {
        @BindNode(withPath:"timer") var startTimer: SwiftGodot.Timer
        @BindNode(withPath:"music") var music: AudioStreamPlayer
        @BindNode(withPath:"mobTimer") var mobTimer: SwiftGodot.Timer
    
        func newGame () {
            startTimer.start ()
        }
    }

    If you omit the withPath parameter, depending on your system, the result might not resolve at runtime.

    See also

    • SwiftGodot API differences to GDScript

      This document lists some common differences between GDSscript and SwiftGodot.

      Read More
    • Variants

      Follow up on the fundamental building block of Godot’s data types.

      Read More
    • Exports

      In Godot, class members can be exported. This means their value gets saved along with the resource (such as the scene) they’re attached to. They will also be available for editing in the property editor. Exporting is done by using the

      Read More
    • Signals

      Signals in Godot are used by objects to post interesting events that are taking place, and can be used by users to easily add behavior and react to changes.

      Read More
    • Using Custom Types

      You will typically extend the functionality of your Godot game by creating classes that derive from one of the various Godot types and adjust the behavior accordingly.

      Read More
    • Running Code in the Godot Editor

      There are cases where you might want some of your Swift code for your extension to run while it is being used in the Godot Editor.

      Read More