The Godot Q&A is currently undergoing maintenance!

Your ability to ask and answer questions is temporarily disabled. You can browse existing threads in read-only mode.

We are working on bringing this community platform back to its full functionality, stay tuned for updates. | Twitter

0 votes

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?

in Engine by (68 points)

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

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 '+'."

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?

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?

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.

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


Please log in or register to answer this question.

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 Frequently asked questions and 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 [email protected] with your username.