• Godot HelpProgramming
  • Singleton problem: "singleton can't assign a new value to a constant" but it's not constant!

I am trying to make a global variable and i saw singletons are the "global variables" and so i tried to create a singleton but i get an error that says "singleton can't assign a new value to a constant"

Have you ever encounter this problem? What could be the solution to this?

What does the line of code look like? I have not encountered this error myself, but I have used Singletons in Godot several times, generally as a data blob.

Example (untested):

# singleton named "Globals"
extends Node
var example_variable = 0

# Using the singleton (different script)
func _ready():
	print (Globals.example_variable)
	Globals.example_variable += 1
	print (Globals.example_variable)

@TwistedTwigleg said: What does the line of code look like? I have not encountered this error myself, but I have used Singletons in Godot several times, generally as a data blob.

Example (untested):

# singleton named "Globals"
extends Node
var example_variable = 0

# Using the singleton (different script)
func _ready():
	print (Globals.example_variable)
	Globals.example_variable += 1
	print (Globals.example_variable)

Now it says "The indefinder Globals isn't declared in the current scope"

Did you set up the singleton in the Autoloads tab (documentation) and named the singleton "Globals"?

The error is saying that Globals has not been declared, meaning it does not think it exists, which shouldn't be the case if the singleton is setup correctly, as the singleton should be accessible from any script in the project.

Ok, now i followed the documentation and named the singleton "Globals" but now i get another error which it says "Invalic Operands 'Object' and 'int' in operation '+'."

Hmm, strange. I'm not totally sure why it thinks Globals.example_values is an object, since the variable should be set to an Integer. Maybe the code is being called before the singleton has a chance to initialize?

from another forum they told me that the line with coins = root.get_child(root.get_child_count() - 1) is wrong because coins is no longer an int after that happens and so later the Global.coins += 1 fails.

I removed it and i print the Global.example_variable and it worked Thanks for your replies!

3 years later