Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
Tags

How do i pass a variable trough prefab or nodes?

A topic by Cat With Keyboard created Sep 12, 2023 Views: 127 Replies: 2
Viewing posts 1 to 3

I don't use godot,I usually program on unity but I wanted to learn and use godot and I can't just find a tutorial or something on the documentation that helps me

(Also I'm not english speaker,im Cuban so I speak spanish,sorry if I don't have a proper English)

Submitted(+1)

Hi, I'm probably a bit too late with this response for it to actually help in the game jam, but here it is:

There are many different ways you can communicate between Nodes. You dont need to use all of them, just chose one that works for whatever you want to do.

#1 Call down: Lets say we have a node "Parent" and its child node "Child". If you're up in the hierarchy (Parent), it is recommended to access child properties by just calling them/their getter, setter methods.

You can get a reference to the Node by its name like this inside a function (both lines do the exact same thing):
get_node("Child").get_x()
$Child.get_x()

To get a reference of a node at a script level scope, you can also use @onready like this:
@onready var child = $Child

#2 Signal up: If the child node wants to access the parent node, you again have multiple options:
If you know the exact relative or absolute path of the node you want to access, you could just use:
get_parent().get_x()
get_node("/root/Parent").get_x()

However, since this can become messy really quickly, its better to use signals here, eg:

Parent:

func _ready(): $Child.x_changed.connect(set_var)
func set_var(x): print(x)

Child:

signal x_changed(new_value)
func _process(delta): if Input.is_action_just_pressed("ui_accept"): x_changed.emit(1)

You can also simply connect signals in the editor in the Node tab.

#3 Autoload: If you add a Node in the Autoload tab in the project settings, the node will be accessible from every other node since its on top of the hierarchy. If you for example add the Node "GameManager" with the script:
var x = 10

then you can just access x from anywhere with GameManager.x.

This is extremely useful for global settings, etc.


Hope this helps :)
Submitted(+1)

Another way to pass data is the "Event Bus" pattern:

In a singleton (autoload) called gd define all your events as signals

e.g.
```signal player_died
signal player_collected_item item```

Then in game trigger events like this:

`GameEvents.player_died.emit()`

Then in other nodes listen for the event like so:

`GameEvents.player_died.connect(self._player_died)`