RobotRampage Background Music doubles after pressing "Menu" button [RESOLVED]

As the title says, after completing the RobotRampage tutorial, there is an issue with background music: each time player press the “Menu” button, the “Menu” scene loads together with the music, which ends up with multiple copies of BGM playing simultaneously.
Could somebody explain some way to fix it?

Whoa! Am I genius?:grinning: I’ve searched through the documentation and could find the solution to this problem!
In the Game.cs script after the class declaration I added a new variable:
GameObjcect bgm;
and then I added these two lines inside the MainMenu() method above the SceneManager.LoadScene:
bgm = GameObject.Find("BackgroundMusic");
Destroy.bgm;

Chapter 13, section ‘Adding sound to the Game’ (for SoyBoy) says:

When playing sound effects, especially from locations like the game Update() method, you’ll want to ensure they are not already playing, otherwise you could end up with sound loops playing over each other.

I thought that may be I can use solutions described there, but as I’m still a newbie to programming, I couldn’t find a proper application of those methods to RobotRampage.

Nevertheless, now every time player pushes Menu button, the old copy of BackgroundMusic object (which we decided to DontDestroyOnLoad(gameObject) in BackgroundMusic.cs script) is destroyed and doesn’t overlap with newly loaded one. :slightly_smiling_face:

1 Like

Haha nicely done!

The GameObject.Find() method is quite useful like that to find objects and destroy/work on them at runtime. Just make sure you don’t use it too often (like calling it from the main Update() loop in your scripts, as it’s an expensive method to call in terms of performance. But using it once off like you have in the start of the menu load is perfectly OK :slight_smile:

1 Like

This topic was automatically closed after 166 days. New replies are no longer allowed.