Search code examples
variablesinstancegodotgodot4

I can't acces variables of an instanciated scene in an other script


So I have this scene with a variable, per exemple : @export name: string if a get 3 of these in my main scene and all change their 'name', how can I acces that variable from the script that controls the main scene and not the one that controls the 'caracter' scene

hope it's clear, thank you


Solution

  • Solution Approach: Instance the Scenes: Ensure that the scenes (like the character scene) are instanced in the main scene.

    Accessing Exported Variables: You can access the exported variables (e.g., name) from the instanced scene by using get_node() or storing a reference to the instance.

    Example:

    1.Character Scene (Character.tscn) In your character scene, you have an exported variable name:

    #Character.gd (attached to the character scene)

    extends Node2D

    @export var name: String

    2.Main Scene (Main.tscn) In your main scene, you’ll instance the character scenes and then access their name variables:

    #MainScene.gd (attached to the main scene) extends Node2D

    @export var character_scene: PackedScene

    var character_instances = []

    func _ready():

    #Instance 3 characters
    
    for i in range(3):
        var character = character_scene.instantiate()
        add_child(character)
        character.name = "Character " + str(i + 1)  # Set the name
        character_instances.append(character)
    #Now you can access the name from the main script
    for character in character_instances:
        print(character.name)  # This will print each character's name
    

    Key Points: @export var character_scene: PackedScene is used to export the scene (you can assign the PackedScene in the Godot editor).

    Each instance of the character is created by calling instantiate() on the PackedScene.

    You access the name variable of each character by directly referencing the instance.

    Accessing Variables Across Different Scenes:

    By instancing the scenes and storing references (character_instances in this case), you can access and modify variables (name in this case) from the main scene script.

    Visit Pisqre for the latest insights! 💡