How to define a global variable?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By GunPoint
:warning: Old Version Published before Godot 3 was released.

How i can define a global variable?
I want to acces the same variable in other objects and other scenes
I couldn’t find any info about global variables in the docs

:bust_in_silhouette: Reply From: quendera

Hi,

I reccomend you follow the begginer tutorials to learn all these simple things here:

You can define a global var to any script by doing so outside a function:

extends Node
#myscript.gd is attached to myscene.tscn    

var myglobalvar
    
func _ready():
    var mylocalvar

To access this function from a script other than myscript.gd just use get.node(“…/path/to/myscene.tscn”).myglobalvar

:bust_in_silhouette: Reply From: jospic

Using a singleton:

Regards.
-j

:bust_in_silhouette: Reply From: dwpasquinelli

the answers that have already been given are good for what you’re asking about, but the actual answer is that there aren’t global variables in gdscript. there is no global namespace, and there is no way to inject things defined in one namespace into another. yes, you can look up any node in a scene and access its member variables, but that’s not a global variable, no matter if the node is implicitly added to the scene.

let’s say you wanted to have a separate file full of game related constants and types. you can do that and (pre)load the file anywhere you want to use it.

var smeg = preload("res://utils/constants.gd")

that’s basically a global, right? no, because this is how you refer to anything defined in constants.gd:

smeg.SOME_CONSTANT

SOME_CONSTANT is not in the global namespace.

strictly speaking there is a global namespace, but users can’t add to it.

I can not change value of this variable from other script

bappy | 2019-05-19 18:06