How can I stop my spawner from lagging when spawing scenes in an endless runner?

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

I’m trying to make a 2D endless runner.

I want to set up a few scenes of obstacles and then spawn the scenes in a random order. But the game lags whenever I spawn a scene that has more than a few obstacles in it.

I’m completely new to this so the answer might be obvious. But is there any way to improve performance without decreasing the amount of nodes in each scene that I’m spawning?

Here is the code for my spawner:

   
export (Array,PackedScene) var scenes
var random_scene = RandomNumberGenerator.new()
var selected_scene_index = 0

func _ready():
	random_scene.randomize()
	selected_scene_index = random_scene.randi_range(0,scenes.size()-1)
	var tmp = scenes[selected_scene_index].instance()
	add_child_below_node(self,tmp)

func _on_Area2D_area_exited(area):
	random_scene.randomize()
	selected_scene_index = random_scene.randi_range(0,scenes.size()-1)
	var tmp = scenes[selected_scene_index].instance()
	add_child_below_node(self,tmp)

Thanks for the help!

:bust_in_silhouette: Reply From: yrtv

Preload all scenes used with one of the methods above.

Compile any shaders used before starting run like explained here https://youtu.be/Cg4ZT6X0ghs