How to track NPC movement when switching scenes?

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

Hello :slight_smile:
I’m currently working on a project were the NPCs are supposed to walk around following a daily routine. Currently they have a FiniteStateMachine attached to them, which tells them were and how to move. This only works when they are active in a scene though. They do not move, if the player is not around. I am unsure how exactly to approach this problem. Making all NPCs autoloads to make their positions and states persistent seems a bit excessive. Any Ideas for a better design?

I haven’t tested this yet so I’m not sure it’ll work… but, you could make an autoload script called “NPCInstances” for example, and inside of it store a reference to each NPC that you will refer to exclusively. That way, even when theyre not in a scene, they’re still "alive’ if you will. Whenever you wish to remove them, you’ll have to use “remove_child” instead of “queue_free” so that the instance isn’t lost.

I don’t know if they’ll still run though if they only exist in reference?
Perhaps you could have a _process function in the autoload that updates the NPCS every frame or few frames?

DigitalDrako | 2022-10-14 18:20

:bust_in_silhouette: Reply From: Inces

You mean they are supposed to be living, moving, doing all sorts of things under the hood, when they are not rendered ?

If this is so, You will have to code them as persistent objects, not as Node2D inheristants, but just Node. They will have to execute their behavior code in process or setget or on_timeout at all times. Switching scenes should only trigger creating sprites and visualizing behavior of only these NPCs, that are supposed to belong to new scene.