Topic was automatically imported from the old Question2Answer platform.
Asked By
Lajbert
Hello,
I’m new to Godot, I have the following Node setup in my scene:
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…
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";
}
}