0 votes


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

Godot version 3.5.1
in Engine by (53 points)

1 Answer

+2 votes
Best answer

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

by (84 points)
edited by

Thanks mate, it works!

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.