SemihERDEM
SemihERDEM

Reputation: 21

Godot Invalid to get index 'x' (On Base: 'Node (a.gd)')

im trying to hold a path to a game object (bat.tscn) in a script and use it to instanceate a object from a different script. Name of the script that holds the variable is called a.gd and the one that is responsible for instantiating is b.gd and the name of the variable is x. But for some reason every time i try to use the variable it gives me an error;

Invalid to get index 'x' (On Base: 'Node (a.gd)')

a.gd;

func _process(delta):
var SlotOne = $"res://Objects/Weapons/Bat.tscn

b.gd;

onready var InvManager = get_node("../a") #gets the script.

func _physics_process(delta):
    changeWeapons()

func changeWeapons():
    if Input.is_key_pressed(KEY_1):
        load(InvManager.SlotOne)
    elif Input.is_key_pressed(KEY_2):
        print("2")
    elif Input.is_key_pressed(KEY_3):
        print("3")
    elif Input.is_key_pressed(KEY_4):
        print("4")    

any ideas how can i fix this issue? Im pretty new to the game engine so im kinda stuck here.

Upvotes: 2

Views: 4682

Answers (3)

programmer master
programmer master

Reputation: 1

Well so it looks like you are just loading the scene instead of instancing it

this might help

first make sure that a.gd is a autoload script

then instead of writing the a.gd like this

func _process(delta):
    var SlotOne = $"res://Objects/Weapons/Bat.tscn

write it like this

 extends node

 const SlotOne= preload("res://Objects/Weapons/Bat.tscn")

then write this on b.gd

func _physics_process(delta):
changeWeapons()

func changeWeapons():
    if Input.is_key_pressed(KEY_1):
        var Bat_instance = A.SlotOne.instance()
        Bat_instance.position = Vector_2() #some position
        self.add_child(Bat_instance)
    elif Input.is_key_pressed(KEY_2):
        print("2")
    elif Input.is_key_pressed(KEY_3):
        print("3")
    elif Input.is_key_pressed(KEY_4):
        print("4")  

Upvotes: 0

Theraot
Theraot

Reputation: 40295

It appears you declared SlotOne inside of _process. That makes it a local variable. In other words, this variable will only be availabe inside that _process, and thus, you cannot reach it from another script.

Define the variables you want to reach from other scripts outside of any method (func) - the language guidlines encourage to place them near the start of the file, before any methods.

Upvotes: 1

programmer master
programmer master

Reputation: 1

also a possible explanation is that instead of using or instancing the node you are trying to access it

so first try to add the node to the main scene like this

get_tree().current_scene().add_child("#the path to a.gd")

but anyways only the code can can tell us what is wrong

Upvotes: 0

Related Questions