godot 4 gdscript effects all scene instances

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By anthonyirwin82


I have a scene for respawning locations that I have multiple duplicates of in my level scene.

When my code runs it affects all the respawn scenes and not just the one that the code should be running on.

I am not sure why this is happening.

My code is below:

extends Node2D

var empty_chamber_sprite: CompressedTexture2D = preload("res://Scenes/RebirthChamber/RebirthChamberEmpty.png")
var player: CharacterBody2D

func _ready() -> void:
    player = get_tree().get_first_node_in_group("Player")
    if player == null:
        push_error("Error: Unable to get the player node in RebirthChamber")
    player.connect("respawn", on_respawn)

func on_respawn() -> void:
    # TODO: create player death animation prior to respawning

func respawn_at_rebirth_chamber() -> void:
    var respawn_points: Array[Node] = get_respawn_points()
    var nearest_respawn_point: Node2D = respawn_points[0]
    for respawn_point in respawn_points:
        if respawn_point.global_position.distance_to(player.global_position) \
                    < nearest_respawn_point.global_position.distance_to(player.global_position):
            nearest_respawn_point = respawn_point
    player.global_position = nearest_respawn_point.global_position
    # Remove rebirth chamber from group so that it cannot be used a a rebirth point
    # TODO: animation of player being reborn in rebirth chamber
    nearest_respawn_point.get_node("Sprite2D").texture = empty_chamber_sprite

func get_respawn_points() -> Array[Node]:
    return get_tree().get_nodes_in_group("RebirthChamber")

func get_respawn_points_count() -> int:
    return (get_respawn_points()).size()
:bust_in_silhouette: Reply From: Vadalken

I don’t think your problem is in the code you have posted here. respawn_at_rebirth_chamber() is the only function that changes the respawn chambers, and it only acts on one every time it is called.

I would guess the problem has to do with the player “respawn” signal being emitted many time and/or some function call being done more times than intended.


I added some print messages to debug and the code was being executed by every rebirth chamber.

I moved the code out of the rebirth chamber and it is now working as expected.

anthonyirwin82 | 2023-04-11 11:42