How can I transfer data/characters between scenes globally?

Godot Version

Godot 4

Question

How would I move characters and data between scenes globally? I am trying to recreate the battle screen from the original Gameboy Pokémon Red and Blue, but I am new to global variables and instancing objects across scenes. I would like to have a feature that when the player encounters an enemy from the main scene, then that enemy would be transferred to the battle scene template I’ve made, with the characters current stats and the sprite and health of the enemy, and then to have that enemy disappear when the player finishes the battle and have their health retain from the battle.

However, I am not sure how to do this when working with multiple scenes, and while I have used auto load and singletons, I am not sure how to work with them very efficiently in areas like this. Transferring data across scenes like this and saving it is mainly what I need help with.

Rather than transferring the character, you want the data.
In the main scene, the enemy will just be a sprite that can be encountered.
That encountering initiates the battle scene and specifies which enemy it is.

The battle scene then instantiates the enemy.

Something like this:

main_scene_enemy.gd

extends Node2D
...rest of code

func encounter():
    emit_signal("initiate_battle", self.name) # connect this signal to _on_initiate_battle in the battle_scene

battle_scene.gd

extends Node2D
...rest of code

var battle_scene_enemy = preload("res://scenes/battle_scene_enemy.tscn")

func _on_initiate_battle(enemy_name):
  var enemy = battle_scene_enemy.instantiate()
  enemy.initialize(enemy_name)

battle_scene_enemy.gd

extends Node2D
...rest of code

var name

func initialize(enemy_name):
  self.name = enemy_name
  var enemy_stats = load("res://resources/enemies/" + enemy_name + ".tres")
  # use those stats for this enemy

enemy_resource.gd

extends Resource

@export var health: int
...rest of code
1 Like

Another way to do it if you want to use a separate scene for each enemy:

Instead of having a battle_scene_enemy template which you attach a resource to, you can use a .tscn scene for each enemy.

Something like this:

main_scene_enemy.gd

extends Node2D
...rest of code

func encounter():
    emit_signal("initiate_battle", self.name) # connect this signal to _on_initiate_battle in the battle_scene

battle_scene.gd

extends Node2D
...rest of code

func _on_initiate_battle(enemy_name):
  var enemy = load("res://scenes/enemies/" + enemy_name + ".tscn").instantiate()
  ...rest of code

battle_scene_enemy.gd

extends Node2D
...rest of code

@export var name: String
@export var health: int

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