+3 votes

Hey, so I'm working on a simple 2D quiz game, and I've set it up with multiple scenes, you go from the main menu scene, to the question category scene and then you're taken to the quiz scene.

So I'd like to play a global song that automatically plays when you launch the game and as you play through it.

One method that I have right now is I've set up a SamplePlayer and I've attached it to the main menu scene. It works, but when I change scenes, it stops playing and is interrupted.
I'm assuming that if I set up the same SamplePlayer on the other scenes the music will also get interruped and start all over again, which I don't want.

So TLDR; How do I set up a song to be played throughout multiple scenes without interruption? Thanks.

in Engine by (18 points)

1 Answer

+2 votes

I suppose you can create a scene that would be loaded globally everytime.
You would put the SamplePlayer / StreamPlayer there.

You can see the autoload logic here: https://godot.readthedocs.io/en/stable/learning/step_by_step/singletons_autoload.html

But the difference from that documentation to your case, is that you would not be creating a script only, but a scene (with a script if needed, I guess).

So, assuming your SamplePlayer node is named "samplePlayer", and the global scene is named "global.tscn", you could always access it from anywhere in the code as global.get_node("samplePlayer") .

Or if you attach a script to that global scene you could save the player in a variable, var samplePlayer = get_node("samplePlayer") and access it from outside asglobal.samplePlayer

by (386 points)
edited by

But how would I play the sounds? Is global.get_node("samplePlayer") enough to get it to play the song? Don't I have to use the play function?

Yes, you still have to use the play() function.

You can add/attach a script to the global scene, and there you can use the play.
So if you want the music to start immediately playing you can do it in the _ready function in script:

_ready():
   get_node("samplePlayer").play()

Or even more simple, on the scene editor panel, if you select the samplePlayer node there should be an autoplay option.

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.