Null reference error on AddChild (C#)

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

I’m getting a strange null ref error when trying to AddChild (C#, it’s not running in _Ready)

Node b=((PackedScene)ResourceLoader.Load(scenePath)).Instance();

I’ve checked in the debugger and neither b nor the root are null. However, I’m getting this error:

E 0:00:02:0913   System.NullReferenceException: Object reference not set to an instance of an object. 
  Node.cs:386 @ void Godot.Node.AddChild(Godot.Node , Boolean )()
:bust_in_silhouette: Reply From: jarlowrey

I tested with AddChild(new Sprite()) and that worked fine. The issue ended up being that I was not calling base._Ready() when I overrided that function. That was causing a null ref somewhere and the engine was just giving a very poor error message.

I ran into the same problem, but the cause/solution was different (so I’m leaving this comment here for posterity). I have two classes, Parent and Child. Parent is attempting to create a new Child by instantiating the class:

var child = new Child();

This AddChild(child) is where the error was being thrown. The cause was that in Child I had exported a PackedScene so that I could set it in the Godot editor, like this:

PackedScene MyScene { get; set; }

But when debugging I noticed that, even though I had set MyScene in the editor, its property on Child was null at runtime. Removing the [Export] Attribute and changing the declaration to:

PackedScene MyScene { get; set; } = ResourceLoader<PackedScene>(PathToScene);

solved the problem for me. I’m not sure if this is a known limitation of C#, VSCode (where I’m writing my C#), or of my own feeble mind.

kentbot | 2021-06-16 04:11