Performance: Background music management
This concept affects the game's frame rate and load times by managing audio playback efficiently.
Jump into concepts and practice - no test required
void Start() {
audioSource.Play();
}void Update() {
if (!audioSource.isPlaying) {
audioSource.Play();
}
}| Pattern | CPU Usage | Frame Drops | Audio Quality | Verdict |
|---|---|---|---|---|
| Repeated Play calls in Update | High (checks every frame) | Frequent | Audio glitches | [X] Bad |
| Play music once at Start | Low (single call) | None | Smooth playback | [OK] Good |
| Load audio at runtime | High (blocking load) | Severe | Possible stutter | [X] Bad |
| Preload audio in Awake | Low (preload once) | None | Smooth playback | [OK] Good |
| Abrupt music switch | Low | None | Audio pops | [!] OK |
| Fade music switch | Low (small overhead) | None | Smooth transition | [OK] Good |
DontDestroyOnLoad with background music in Unity?DontDestroyOnLoadDontDestroyOnLoad on the music GameObject, the music keeps playing without restarting or stopping between scenes.DontDestroyOnLoad keeps objects alive across scenes [OK]Play() to start playing audio clips.Play() is a valid AudioSource method to play sound.AudioSource audioSource = gameObject.AddComponent<AudioSource>(); audioSource.clip = backgroundMusicClip; audioSource.volume = 0.5f; audioSource.Play(); Debug.Log(audioSource.isPlaying);
isPlaying propertyisPlaying returns true if the audio is currently playing, which it is after Play() is called.void Start() {
AudioSource audioSource = GetComponent<AudioSource>();
audioSource.clip = backgroundMusicClip;
audioSource.Play;
}audioSource.Play; is missing parentheses, so it does not call the Play method.audioSource.Play();.DontDestroyOnLoad keeps it alive across scenes, preventing duplicates.