Reputation: 79
I have been learning Godot 4 with C# and I came across a problem related to getting a reference to a node in a script.
public override void _Ready()
{
AudioStreamPlayer2D audio = GetNode<AudioStreamPlayer2D>("AudioPlayerThingy");
audio.Stream = GD.Load<AudioStream>("res://DRUMS.wav");
audio.Play();
}
It keeps saying that the AudioStreamPlayer2D
Node, "AudioPlayerThingy," is not found relative to its sibling, a sprite2d renderer. I have made sure that I have not made any typos, and the tutorial I am following is from Godot 3 so I dont know if it is outdated for this question. What do I do here?
Upvotes: 1
Views: 177
Reputation: 40295
This expressions:
GetNode<AudioStreamPlayer2D>("AudioPlayerThingy")
Would have Godot try to retrieve a child AudioStreamPlayer2D
that has a name
set to "AudioPlayerThingy"
.
However, you say:
It keeps saying that the
AudioStreamPlayer2D
Node, "AudioPlayerThingy," is not found relative to its sibling, a sprite2d renderer.
If you want a sibling, you would do this:
GetNode<AudioStreamPlayer2D>("../AudioPlayerThingy")
This expression would have Godot try to retrieve a sibling AudioStreamPlayer2D
that has a name
set to "AudioPlayerThingy"
.
I'll point out that if there is any chance that you would move those Node
s around in the scene tree in the future, that would break. Usually we assume that when we move a Node
in the scene tree, we move it with its children. However, here you would have a Node
depending on a sibling, which is a non-obvious dependency.
Consider setting the Node
to have a unique name in the scene (the option is in the context menu of the Node
in the scene dock). With that enabled, you could do use this:
GetNode<AudioStreamPlayer2D>("%AudioPlayerThingy")
This expression would have Godot try to retrieve a AudioStreamPlayer2D
that has been set to have a unique name in the scene, and that name
is set to "AudioPlayerThingy"
.
For people coming from Unity:
Godot does not have a scene/prefab distinction. Here when I say "unique name in the scene" it refers to the scene being edited, which might be instanced multiple times, and each one would have an instance of the Node
that has an unique name, all having the same name... The name is unique within the instance.
Also "SpriteRenderer" is not a thing in Godot.
Upvotes: 2