C# Constructors on Godot Nodes

Godot Version 4.2.2

This might be a stupid question, but if I have a C# script that inherits Node, can I assume the parameterless constructor is called when that Node is instantiated, either at game/scene start, for Nodes placed in the editor, or when instantiated for nodes that are created by PackedScene.Instantiate()? Are there any gotchas or exceptions? Essentially, is it sensible to do some of the initialization in the constructor?

As far as I’m aware and have seen all c# code is just that, compiled c#. Ie it’s not interpreted by godot. So you can expect it to act like any other piece of code, in that a constructor will always be ran for new().

I will add though that i would consider myself still fairly new to godot, so take that with a grain of salt :smiley:

1 Like

why don’t make constructor and check for your self?

using Godot;

namespace TestCon;

public partial class SceneWithCustomConstructor : Node2D
{
	SceneWithCustomConstructor()
	{
		GD.Print("Constructor Called");
	}
}
using Godot;

namespace TestCon;
public partial class SceneScript : Node2D
{
	[Export] PackedScene scene;
	public override void _Ready()
	{
		GD.Print("_Ready Called");
		var node = scene.Instantiate();
		GD.Print("_Ready Finish");
	}
}

obraz

2 Likes

Thanks, yes, I’ve done that and the constructor has run as I would expect. My concern is that there could well exist a corner case method of instantiating I’m not yet familiar with, being quite new to Godot, that would come back to haunt me in the future if I used that all over the place.