+2 votes

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

in Engine by (400 points)

3 Answers

+3 votes
Best answer
by (1,466 points)
selected by
+1 vote

Hi,

I reccomend you follow the begginer tutorials to learn all these simple things here:
http://docs.godotengine.org/en/stable/learning/step_by_step/index.html

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

by (25 points)
+12 votes

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.

by (42 points)

I can not change value of this variable from other script

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.