game-developmentgodotgdscriptgodot4

Godot is returning a null value for a very real reference


I am making a character-switching system, where I want the camera to move to the player that is currently active.

I am storing the values for the players in an array, where I will cycle through the values to hold the players.

var Chars = [$Papery, $Erasey, $Pencily]
var charnum = 0

And then the function is called when the key q is pressed.

func _input(event: InputEvent) -> void:
    if event.is_action_pressed("q"):
        transitioning = true
        if charnum == 2:
            charnum = 0
        else:
            charnum = charnum + 1
        CurChar = Chars[charnum]
        await $Camera2D.global_position - CurChar.global_position < Vector2(5,5)

However, the Char array values are <Object#null> when printed.

I've tried changing the forms that the references were taking in the array, and I've been looking through settings and documentation, but I can't find anything.


Solution

  • In Godot nodes are runtime objects. That means you must use the decorator @onready to actually invoke get_node('name') or you have to initialize variables into the _ready() function. Read GDBScript reference for more detail

    Note: The way you created the list could actually work, but it's a bad practice and not the "Godot way" of doing that (the error you got is the demonstration). The way you created the list is good only if "players are already present/been instantiated and you need to reference them".

    If this doesn't work, are you sure you referenced well nodes from the tree? Is $Papery actually the correct path to follow to get the node from the current node?

    Please to be sure of that Ctrl + Left click on node from the scenetree and drag that into your script; Godot will automatically create an @onready variable with correct path. See Node reference

    Greetings