C# GetNode with Nested Scenes — Can't Find Existing Node

Godot Version

Godot Engine v4.2.2.stable.mono.official

Question

I need help understanding how GetNode works. I’m trying to do a basic GetNode call, but all my attempts return null.

I have a scene nested within a scene:

Game (Node2D)             // Main scene
↳ GameManager   % (Node)  // Nested scene
 ↳ ScoreManager % (Node)
  ↳ ScoreLabel  % (Label)

The ScoreLabel is a child of the ScoreManager, which is a child of the GameManager. The GameManager scene is then nested into the main game scene.

This is the script attached to my ScoreManager:

public partial class ScoreManager : Node {
	// Properties
	public int score { get; private set; }
	private Label scoreLabel;

    // Constructor
	public ScoreManager() {
		scoreLabel = GetNode<Label>("%ScoreLabel");

		if (scoreLabel is null) {
			GD.PrintErr("The ScoreLabel does not exist in the SceneTree.");
		}
	}
}

I’ve tried every path combination I can think of for GetNode<Label>(""), but they always return null. What is the correct code to get this node?

Have you tried running your constructor code in _Ready()? With the way Godot builds the scene on instantiation, you can’t get a child node during initialization (_init() in GDScript – constructor in C#).

Here’s a description of what I’m referring to:

2 Likes

That worked! Here’s the updated code:

public partial class ScoreManager : Node {
	public int score { get; private set; }
	private Label scoreLabel;

	public override void _Ready() {
		scoreLabel = GetNode<Label>("%ScoreLabel");

		if (scoreLabel is null) {
			GD.PrintErr("The ScoreLabel does not exist in the SceneTree.");
		}
	}
}

Thanks for your quick reply. I had been banging my head against this problem for like an hour. Much appreciated.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.