Ready function called twice when scene is changed programmaticaly

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

Hello,
The “_Ready” function of my scene is called twice when I use ChangeSceneToPacked to load it.

private void start()
{
	PackedScene packedScene = ResourceLoader.Load<PackedScene>("res://scenes/MainGameScene.tscn");
	GetTree().ChangeSceneToPacked(packedScene);
}

I checked with a simple “GD.Print()” that my function is called only once and it’s called only once.

Also when I use the following code my scene also call _Ready twice and it seems there is also two _Process executing at the “same” time.

MainGameScene mainGameScene = packedScene.Instantiate<MainGameScene>();
	
root.AddChild(mainGameScene);
root.RemoveChild(this);

Did I do something wrong or it’s the expected behaviour ?

:bust_in_silhouette: Reply From: M.Kh

I don’t understand the essence of your problem, but I do know this:

  • I am not familiar with ChangeSceneToPacked so my solutions may not work with this method.
    And for this reason, I suggest you use reload or ChangeSceneToFile to reload the scene, although you know the project better and it seems that you have a special reason for this. If you use this method and you want multiple scenes at the same time, use automatic loading or loading in script.
  • If you run the scene again, the _ready function is also executed once.
  • However, if you don’t want to run it, call the functions you want to run again instead of reloading the page.
  • If this case was too long for you, you can remove the codes inside _ready and execute the part you want by saving a variable in the memory that says how many times the code has been executed.
  • You can even use another similar scene without the _ready function and use the second scene instead of loading the page into the main scene.

I hope I have helped; If there’s a bug or it’s not what you want to do, you can send it with more information, I’ll definitely try to solve your problem.