How do you pass a variable in one script to another script?

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

Noob here - I have a main script: “MainScript” attached to a label where I want to access an array: “townLocations” in another script: “Town” (“Town” script is not attached to a node)
How would I best go about doing this?

:bust_in_silhouette: Reply From: JCJL

You could use Autoload to accomplish it. In Project/Project Settings/Autoload, add the Town script file and enable it.
Any variables and functions in your Autoload will be accesible from anywhere so you could do in MainScript:

$label.text = Town.townLocations[0]

Or do whatever you need with said array/variable.

This works, however as I understand it, it is inefficient.
How I solved it in my case was to put the variables in a class that inherits from my main script and then instantiating the class in the main script, thus allowing me to use the variable within the town class’ constructor

In Town script:

extends Main

class_name Town

var	buildings

func _init():
	buildings = ["the tavern", "the farm", "the great hall"]

In main script:

var town = Town.new()

print(str(town.buildings[1]))

Open to feedback.

Scorch | 2023-04-02 13:35

:bust_in_silhouette: Reply From: aidave

Use NodePaths