Godot Version
4.5
Question
I’m trying to make a health system and in doing so need to access the players script. I’ve done this countless other times in enemy scripts but for some reason in the container script that has the health, I can’t access the player’s script.
The player has a class_name of Player and there’s a gamemanager script that has player’s type as Player (the class name of the player)
In an enemy I defined the player using
@onready var player = gamemanager.player
But when I use that same line of code in the heart container it’s null. The container for the health is a child of the player’s camera incase that’s of any use. I’ve tried accessing it through get_parent().get_parent() and so forth but to no avail
This is the scene tree and heartContainer is the node in question.
I’m happy to provide any more needed details!
Using the @onready variable player is what doesn’t work. if I entirely use gamemanager.player.whatever it works fine
The heart container is ready before the player is. If your player sets the gamemanager.player like so
func _ready() -> void:
gamemanger.player = self
Then this code will never run before the heart container’s _ready() or @onready variables, thus a null value
1 Like
Is there any solution to making the heart container ready after the gamemanager or can I set it in some function that’s called later? I have it working by saying gamemanager.player whenever I need to use it but I just don’t like that solution because it seems like unnecessary code.
It should be ready after the gamemanager global, globals are ready first. The problem is that a node, in this case Player, only calls _ready after all of it’s children call _ready. You could use an @export as that isn’t reliant on any code in _ready