I want to kill the player. I have added necessary functionality for that, in the player.gd script:
signal player_died
...
const PLAYER_MAX_HEALTH:float = 100.0
...
var player_health = PLAYER_MAX_HEALTH
...
func _process(delta):
if player_health == 0:
die()
...
func die() -> void:
player_died.emit()
Simple as, and this part of the code works fine (I’ve checked with print() at various spots, all turned out correct)
I have this autoload script, deathmanager.gd:
extends Node
var player_group = null
func _ready()->void:
player_group = get_tree().get_first_node_in_group("Player")
if player_group != null && player_group is Player:
var player = player_group as Player
player.player_died.connect(kill_player)
func kill_player()->void:
print("yuo ded")
Yet it doesn’t work properly, I’ve checked and I definitely haven’t misspelled Player as a group. What mistake am I making? Is this even a feasibly good solution for player death?
func _ready()->void:
player_group = get_tree().get_first_node_in_group("Player")
print("Player: ", player_group)
if player_group != null && player_group is Player:
var player = player_group as Player
player.player_died.connect(kill_player)
print("Connected: ", player.player_died.is_connected(kill_player))
The autoload will be before anything else is loaded
When autoloading a script, a Node will be created and the script will be attached to it. This node will be added to the root viewport before any other scenes are loaded.
You will need to wait a frame for the player to be ready.
func _ready()->void:
await get_tree().process_frame
player_group = get_tree().get_first_node_in_group("Player")
if player_group != null && player_group is Player:
var player = player_group as Player
player.player_died.connect(kill_player)