I'd like events/actions (e.g. pressing a button, defeating a mini-boss, etc.) in one area of the game to affect things (e.g. unlock/open door, enable boss spawn) in other areas that are distinct/distant enough to exist in another scene.
When the trigger and target are in the same scene (e.g. switch opens door in the same room), it's easy enough to add export(NodePath) var door_to_open
to the switch's script so that it has a direct reference to the door and can tell it to open. If I move/rename the door node, I just have to update the NodePath, and immediately get an error if I don't (e.g. target_door = get_node(door_to_open) as Door
and assert(target_door != null)
in the switch's _ready
function).
When they are in different scenes, though, such a link isn't possible (since the target node isn't loaded). I've handled this so far by creating an Autoload/Singleton for tracking door state. When triggered, the switches pass in the name of the door they open (something unique but kinda ugly, like "Building1-Floor7-Door3") and it gets included in a list of open doors. In the _ready
function of the door script, I call into the same Singleton to check whether the door should be open or closed. This works, but is quickly becoming a maintenance headache. Moving things in the scene tree and changing the node path isn't an issue, since each door has a name property associated with it. However, changing the names (infrequent, but happens as I'm building things) breaks the link and requires changing the name in both locations (the door in once scene getting opened, and the switch in some other scene that opens it). The worst part is that forgetting to change it (or just making a typo mistake) just means that the names used by the two ends of the set/get are different, and it just looks like the door is not open yet and no error happens (it's perfectly fine for a door's name to not be in the list; it just means it hasn't been opened). Makes testing/debugging more difficult.
Is there a more straightforward way to establish a (one-way) link between two nodes in different scenes? Or at least to consolidate the name variable so that there aren't two independent String declarations (switch, door) that might get mismatched at some point?