Godot Engine

Godot Engine

In gdscript, how do I reference a file-level variable or function from within a class in that file?
I'm trying to do something like this:
extends Control var score : int = 0 class SampleClass: func function(): if score > 0: print("Score is more than zero")
and I get an error saying "Identifier 'score' not declared in the current scope."
Something very similar happens if I try to call a function that is not in SampleClass from SampleClass. How am I supposed to handle this?
< >
Showing 1-2 of 2 comments
umop-apisdn Dec 13, 2023 @ 7:01pm 
Do you mean a class-level variable?
extends Control class SampleClass: var score : int = 0 func function(): if score > 0: print("Score is more than zero")

Or you might be meaning a "global scope" variable... in which case it might look like this in one file:
extends Node classname SampleClass var score : int = 0
... and you could then reference it in another script as:
extends Node func update_score(new_score : int): SampleClass.score = new_score

See https://docs.godotengine.org/en/3.1/getting_started/workflow/best_practices/what_are_godot_classes.html

Note that the SampleClass could also be an Autoload, in which case you can omit the classname line because it's handled by the Autoload system in Project Settings.

See https://docs.godotengine.org/en/stable/tutorials/scripting/singletons_autoload.html
Last edited by umop-apisdn; Dec 13, 2023 @ 7:09pm
Luminous Dark Dec 13, 2023 @ 8:42pm 
No, I meant defining an inner class within the script of another class, and having the inner class reference the global variables and functions of the outer class. I figured out how to do it by passing an initialization variable to the inner class that is the outer class, like this:
extends Control var score : int = 0 class SampleClass: func _init(root, otherArgs): self.root = root self.otherArgs = otherArgs func function(): if root.score > 0: print("Score is more than zero") sample = SampleClass.new(self, 'initialization parameters')
< >
Showing 1-2 of 2 comments
Per page: 1530 50

Date Posted: Dec 13, 2023 @ 5:54pm
Posts: 2