What is the best way to handle a scene that will be used by lots of scenes?

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

I’m curious about the best way to do what I want to do. (It’s a 2D game)

On my game, I need to spawn lots of enemies, when each one dies, they will spawn some Xp particles, in order to do this I need to instanciate the XpParticle scene. What I am looking for is the best way in terms of performance and a clean code, but I don’t really know how the engine will handle.

Using autoload I made a global instance, so each and every node can see it, but turns out that the only way I can create other XpParticle object, is to duplicate() the global scene, what some people said is bad.

The other way around that I know about is to preload() the scene on each different enemy of the game, what i think that might consume more performance as the game needs to handle more and more objects.

:bust_in_silhouette: Reply From: sarapan_malam

You can create autoloads and add preload variable XpParticle

# global_reference.gd
const XpParticle := preload("res://xp_particle.tscn")

Then on the enemy node you just create an instance

# enemy.gd
func die() -> void:
    # ...
	var xp_particle: Particles2D = global_reference.XpParticle.instance()
	xp_particle.global_position = global_position

Yes, but You need to know, that instantiating particles this way will cause all currently displayer particles be on the same state of emission.
To prevent this You also need to get to material property of your particle → resource property → set local_to_the_scene to true

Inces | 2022-09-05 15:00

oh that’s right, we need to make it unique, thanks

sarapan_malam | 2022-09-05 15:50