Changing Variables from Different Script in Same Scene

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

I am trying to call and change a variable from another script in the same scene.

In one script for my NPC I have:

var needs_ale = true

Then in another script for my player, I am trying to change this value to “False” when my player interacts with this NPC:

func _input(event):
if(canInteract and event.is_action_pressed("action")):
	get_node("World/NPCs/NPC").needs_ale = false

However, I get the error "Invalid set index ‘needs_ale’ (on base: ‘null instance’) with value of type ‘bool’.

I have tried everything I can find. I think my get_node part is not finding the script variable but I’m not sure.

I would appreciate any support!


get_node("World/NPCs/NPC") is not finding the node, because that’s not the proper path. What does your scene tree look like?

kidscancode | 2019-08-12 14:02

My tree looks like this


Nathan_R | 2019-08-12 18:16

:bust_in_silhouette: Reply From: johnygames

There are a few ways you can reference a variable from another script:

  1. Find the proper path of the node which has the script with the variable in question. Your path is probably wrong, maybe you attached the script to a node further down the tree or something.

  2. If you need to get the value of such a variable, you could also instance a new script and get it from there. You could do something like this:

var example = preload("res://Scripts/<script with variable in question>.gd")

    func _ready():
    	scale = Vector2(0.25,0.25)
    	example =
            print(example.<variable in question>)

Note that this method will not change the original value, it will just grab the variable you want and make a copy of it (that’s why you use the new() method)

  1. Use a singleton. Any variables that need to be accessed from the whole game can be autoloaded in the beginning. Check this out: Singletons (AutoLoad) — Godot Engine (3.1) documentation in English

Thanks for the feedback.

I am using a singleton elsewhere and I am able to change the viable etc.

I’m going to look carefully at my node path and see if I can find the solution.


Nathan_R | 2019-08-12 18:19

:bust_in_silhouette: Reply From: kidscancode

Based on your screenshot of the scene tree, I can see where you’re confused.

Calling get_node("World/NPCs/NPC") on your Player script would look for a child of “Player” called “World”, which is exactly why you’re getting a null instance result.

“World” is the scene root, so you need get_node("/root/World") to access it.

I managed to get it to work!

Thank you so much for your help!

Nathan_R | 2019-08-13 05:16