How to access Player instance from a script in another scene

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


I’m new to Godot, I have the following Node setup in my scene:
enter image description here

The Player has its own scene, the Camera doesn’t. I would like to access the Player instance from the Camera script. If I just add [Export] to the variable, I can browse the .tscn file, but that’s not what I need. What I need is to access the object itself that is already instantiated in the scene.
How do I do that in C#? I could store a reference to in a singleton, but that sounds like a horrible idea since I will probably access tons of object references in my game…

Thank you

:bust_in_silhouette: Reply From: Dostoi

Hello Lajbert!

In that simple setup, you could simply add a reference to the “player” node script in the script attached to your camera. Let’s assume your player node has a script named playerControl.cs attached, and your camera has one named cameraControl.cs attached. In cameraControl.cs you could write:

public class cameraControl : Camera
    public playerControl _player;

    public override void _Ready()
        _player = GetNode<playerControl>("../../player"); //this reaches the node with the playerControl.cs script attached

    public void anyFunction()
        _player.anyVariableFromThePlayerScript = "Whatever you want";

Edit: Changed the script’s names for clarity

Thanks mate, it works!

Lajbert | 2023-01-14 09:21