(C#) Null reference error when calling set variable

Godot Version

4.1

Question

Line 20 of my script (Node NewScene = (Node)ScoreScene.Instantiate():wink: is causing a null reference error, even though I have set ScoreScene in the editor, does anyone know what is causing this?

using Godot;
using System;

public partial class ConfirmButton : Button
{
	[Export] public Node MyScene;
	[Export] public PackedScene ScoreScene;
	[Export] public HighScoreManager HighScoreManager;
	[Export] public GameOver ScoreTracker;
	[Export] public TextEdit NameField;
	public void pressed()
	{
		int Score = ScoreTracker.Score;
		string Name = NameField.Text;
		if(Name != "")
		{
			GD.Print(Name + " - " + Score);
			HighScoreManager.UpdateHighScore(Score, Name);
			
			Node NewScene = (Node)ScoreScene.Instantiate();
			GetTree().Root.AddChild(NewScene);
			MyScene.GetParent().QueueFree();
		}
	}
}

You messed up the parenthesis.

Instead of

Node NewScene = (Node)ScoreScene.Instantiate();

It should be:

Node NewScene = (Node)(ScoreScene.Instantiate());

It still sends the error with the parenthesis, but it might be something outside the script, when I loaded it back up this appears to have caused the scenes to not be able to be opened. I reverted to an older version, and am currently trying to find out what is wrong.

check why ScoreScene is null, if you don’t plan access your variables outside this script you should keep them private even you use [Export].

if(ScoreScene)
Node NewScene = (Node)ScoreScene.Instantiate();
else
GD.Print("ScoreScene is null");

Not sure why you delete parent of MyScene

I found out what was wrong, I was accidentally deleting the root scene, because instead of instancing the gameover scene as a child of the gameplay scene I was doing it as a child of the root scene.

1 Like

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