Singleton problem: "singleton can't assign a new value to a constant" but i haven't define it as constant!

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

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?

If you want more concrete help, you should provide the part of your code which is producing that error. That being said, this is precisely the error you’ll get when you do something like this:

const variable_name = 1

func _ready():
    variable_name = 2

njamster | 2020-03-18 19:38

my code:
in Global:
extends Node

var coins = 0

func _ready():
	var root = get_tree().get_root()
	coins = root.get_child(root.get_child_count() - 1)

in the node:

extends RigidBody
var velocity = -50

func _process(_delta):
	linear_velocity.z = velocity

func _on_Area_body_entered(body):
	if body.is_in_group("Wall"):
		Global.coins +=1

Now i am getting an error that says “Invalic Operands ‘Object’ and ‘int’ in operation ‘+’.”

Giannis1996 | 2020-03-18 20:21

So, it looks like Global.coins is a node of some sort (so, an object). You can’t “add one” to a node. What exactly are you trying to do?

jgodfrey | 2020-03-18 23:22

the coins should be an integer variable and everytime a cube touch a wall i want to increase that variable by 1 so, i made global variable (singleton)

I could emit a signal but i want things simplified so i just made a global variable.

How could i do it correct?

Giannis1996 | 2020-03-18 23:37

You initially create coins as an int with coins = 0. However, in your ready function, you overwrite that value with an object from your scene tree with this:

coins = root.get_child(root.get_child_count() - 1)

What are you trying to do there? That’s really where your problem is, as coins is no longer an int after that happens, so your later Global.coins += 1 fails.

jgodfrey | 2020-03-18 23:49

Thank you jgodfrey, that was the problem.
I removed it and then i print the global.variable and it worked!


Giannis1996 | 2020-03-19 08:44