Hey there I’m new to godot and am trying to learn the basics
Right now I have a basic_player and a coin and they are childs of my root node “Level1”
The coin does this:
func _on_body_entered(body):
queue_free()
it’s also supposed to do this:
colllect_coins(1)
The collect_coins function is in global.gd (attached to root node)
It looks like this:
func collect_coins(amount)
coins + amount
(there is a variable called coins in global.gd wich counts coins
I want to call collect_coins in the coins.gd script so I can actually add the coin to the coins variable upon collection
How the duck do I do this? I tried to search for this but I wasn’t able to apply anything I found successfully.
You can AutoLoad your global.gd script under the AutoLoad tab in your Project Settings, then label the global.gd script to be referenced in your coins.gd script.
If done successfully, the code to reference a function from global.gd in coins.gd should look like this:
globalScriptLabel.collect_coins(amount)
For more info, read this: Singletons (Autoload) — Godot Engine (stable) documentation in English
If you have anymore questions, please let me know.
1 Like
There are multiple ways to do this:
The most common one is to call get_node(path)
link to documentation.
You can also do this by using $ notation link to a tutorial.
And you can also use an Autoload, but you shouldn’t abuse this, as this is intended for things that need the Singleton pattern.
this would be an awesome chance to learn how to use signals!
signals are like wires that connect any 2 objects, for example instead of calling collect_coins, instead, try to emit a signal to activate that function in another script, it would look something like this:
#on top of coin.gd
signal collected(int) #you can leave the arguments of the signal empty or add any variable type, in this example a single int for amount of points the coin is worth
func _on_body_entered(body):
queue_free()
emit_signal('collected', 1 )
then on the editor, select the coin node from the tree on the left, then on the right, select node instead of inspector, you should now see the currently disconnected signal called collected. click on it then the node you want to connect to. It will automatically create a function compatible with the signal, but since you already created the function select pick on the bottom right, from there, you can select collect_coins and you’re done.
1 Like