Adding object to typed Godot array gives NullReferenceException

Godot Version

Godot 4.5

Question

I’ve been following along with a GD script tutorial with C# and I’ve come across a problem that has me at a loss. I’ve successfully reproduced it with a very basic script and the solution is probably just something very simple I don’t know.
This is the script:

using Godot;
using System;
namespace MyNamespace 
{
	public partial class MyClass : Node
	{
		public partial class MyType : Resource {}
		public MyType B = new MyType();
		public Godot.Collections.Array<MyType> A;
		public override void _Ready() 
		{
			MyMethod(B);
		}
		public bool MyMethod(MyType b)
		{
			A.Add(b);
			return true;
		}
	}
}

And it produces this error:
bool MyNamespace.MyClass.MyMethod(MyNamespace.MyClass+MyType): System.NullReferenceException: Object reference not set to an instance of an object.

1 Like

Because you need to actually create that object. In the ready function, do:

A = new();

Just like you did with “MyType”

2 Likes