I created and tested an example of what I mean.
- open content drawer and select to Add Blueprint. Select it to be of type GameMode
- open New GameMode Blueprint and click Event Graph and press + to Add Variable. Select the type of Variable to be Audio Component → Reference
- pull off BeginPlay and create SpawnSound 2D, set song wave file
- Pull off Spawn Sound 2D Return Value and Set the variable name Created
- Compile and Save
Click on Level, pull down Settings and select Project Settings. In Maps and Modes, set Game mode base to be the new Game Mode class just selected. Close settings.
- Create box collider and in Event stack select OnComponentBeginOverlap
- Below this, create Get Game Mode, pull off that and cast to your new Game Mode
- Pull off cast return value and select your new AudioComponentRef Variable.
- Pull off that variable and create IsValid (the one with the ?)
- If Is Valid, pull off the AudioComponentRef Variable and find Fade or Stop
- if Isn’t Valid, create Spawn Sound 2D
- pull off the Cast Output and select Set making sure the Target is what it connects to
- Pull off Spawn Sound 2D Return Value to the other pin of Set, then make sure the control path arrows are all connected.
Examples:
Game Mode
Box Collider blueprint
Details:
What is happening here is we’ve created a game mode variable and initial Spawn Sound 2D in our own custom game mode. We’ve made our custom game mode the one that will be used when you hit play. We then created a BP with a box trigger and on collision, have checked to see if a sound is playing, and if so, fade it out. In any case then, we start a new sound.
If you want no sound playing to start with, then delete the Spawn Sound 2D in Game Mode. That’s only there to start a default sound before they hit any colliders.
Improvement:
Our Box Blueprint should have the song to be played specified as a variable rather than put right into the Spawn Sound 2D. This would then let us drop generic copies of the Box Blueprint in the level, and set the specific song wave on each one.