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

Currently I have a control node that I'm using with a label so I can set up a simple ammo counter for my game. In my player kinematicbody2d, I have the variable:

export var ammo = 6

And in my control node, I have:

onready var labelAmmo = "res://Player/".ammo

With this, I immediately get the error "invalid index 'ammo' in constant expression." I am unsure how to remedy this and would appreciate advice.

Godot version Godot Engine v3.3.stable.official
in Engine by (30 points)

1 Answer

0 votes
Best answer

So what you're trying to do is access the ammo property of a String. It's the same as coding "Cool".ammo. Seems silly when you look at it from the computer's perspective. But we've all been there. :)

What you are going to want to do is every time that ammo variable gets changed, emit a custom signal that you create, then have your Control node connect()ed to that signal so it can receive the change and update the UI.

Here are the Godot docs on signals. I highly recommend reading through the entire thing, they're essential for game programming.

Here is also a write up about communicating between nodes:
The diagram in the info box is extremely handy to learn.

Let me know if you need help.

by (3,906 points)
selected by

Would this also retrieve the ammo variable from the player? Or would I have to set up code in the control node that makes its own ammo count that decreases each time ammo_changed is emitted?

Nevermind, got it working! Thank you so much!

You could just use a single variable in the player class to manage your ammo variable:

signal ammo_changed(ammo_left)
func shoot()
    ammo -= 1 
    emit_signal(ammo_changed, ammo)

to connect the two:

onready var player = get_node("Player") # wherever these are located
onready var control_node = get_node("ControlNode") # whereever these are located

func _ready():
    player.connect("ammo_changed", control_node, "_on_ammo_changed")


# gets called whenever  ammo_changed is emitted because of the connect() function
func _on_ammo_changed(ammo):
    labelAmmo = str(ammo)
    # or something like:
    label.text = str(ammo)
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.