- Home /
I can't play an audio before quiting the game
So, i'm very close to finish my game, but i ran into a problem. I want the game to play a little music before the player quits the game(if the player presses Alt + F4 the game plays the audio before quiting). I have search how to do it but i couldn't find anything. How do i do this?,So, i am almost finishing my game but i got into a problem. I want the game to play a little audio before the player quits it (if the player presses Alt + F4 the game plays the audio before quiting). but, i can't find a way for the audio to play before the game quits. how do i play the audio before the game ends?,
Answer by Hellium · Sep 08, 2020 at 10:33 PM
using System.Collections;
using UnityEngine;
public class PlaySoundBeforeQuit : MonoBehaviour
{
[SerializeField] private AudioSource audioSource; // Drag & drop the audio source in inspector
void Start()
{
Application.wantsToQuit -= WantsToQuit;
Application.wantsToQuit += WantsToQuit;
}
private bool WantsToQuit()
{
Application.wantsToQuit -= WantsToQuit;
StartCoroutine(QuitAfterDelay(1f));
audioSource.Play();
return false;
}
private IEnumerator QuitAfterDelay(float delay)
{
yield return new WaitForSeconds(5);
Application.Quit();
}
}
Note: The return value of the wantsToQuit event is ignored when exiting play mode in the editor. IMPORTANT: The return has no effect on iPhone. Application can not prevent termination under iPhone OS.
Your answer
![](https://koobas.hobune.stream/wayback/20220613011506im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple PlayOneShot bug 1 Answer
Audio.Play() not showing up 1 Answer
Copy audio buffer into another component 0 Answers
AudioClip array error 1 Answer
Loading Audio from Asset Bundles not working in Unity 5.2 2 Answers