What does "get_node" actually do?

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

I’m doing the “Code Your First 2D Game With Godot” video tutorial and he uses the $ symbol and says it’s a shorthand for get_node. I read the documentation and it says it “fetches a node” and talks about paths. I don’t understand what fetch or path means in this context. Why does he sometimes put nodes in a script with the $ and sometimes without? What’s the difference? I’ve googled fetch but I’m still not understanding what it does in relation to nodes in Godot.

TLDR: What EXACTLY is the PURPOSE of get_node, i.e. WHAT does it do and by extension WHEN do I want to use it (or NOT use it)?

Thank you!

:bust_in_silhouette: Reply From: Inces

Fetching here means obtaining and memorizing reference to the real object. Reference is like a phone contact of an object,variable or function. When You store reference in some variable, like

var home = get_node("./home")

,than You can use it to make calls to referred node, order it around, but changing this variable will not change node itself, it will only change this “phone contact”. For example:

home.postion = Vector2(0,0)

These will work, real node will be queued free or its position will change. But:

home = get_node("work")

will not transform node “home” into node “work”, it will change variable home to address “work” instead of “home”

In Godot there are certain variable types that are always a reference instead of real value. All objects, arrays and dictionaries are like this. So You don’t really have choice with get_node() :). $ is exactly the same thing as get_node(). The only difference is that get_node utilizes a String, so You can use some constructed String value to dynamically create path for get_node. For example :

var bullet = "bullet"
get_node("./" + bullet).speed = 100

Thank you Inces! That helps a lot.

I think I get it now. I’ll have to practice it a few times to be 100% sure though :slight_smile:

Orgull | 2021-11-15 21:37