Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Why does a sound effect from seperate audio source interfere with background music?

Discussion in 'Audio & Video' started by Jekirutu, Jul 16, 2022.

  1. Jekirutu

    Jekirutu

    Joined:
    Jun 10, 2019
    Posts:
    14
    Hello, I have two audio sources in my scene. One plays music randomly from a playlist. The other plays sound effect when you click on things in the game.

    For some reason, whenever a sound effect is played, the music abrubtly stops and after the sound effect is "finished", it loads another random song. I've never had an issue like this before, and I know that Unity can handle multiple sounds at once. Is there any way to fix this?

    Also, here is the code of the "music player" audio source:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Audio : MonoBehaviour
    6. {
    7.     public AudioClip[] clips;
    8.     private AudioSource audioSource;
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         audioSource = FindObjectOfType<AudioSource>();
    14.         audioSource.loop = false;
    15.     }
    16.  
    17.     private AudioClip GetRandomClip() {
    18.         return clips[Random.Range(0 , clips.Length)];
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update()
    23.     {
    24.         if (!audioSource.isPlaying) {
    25.             audioSource.clip = GetRandomClip();
    26.             audioSource.Play();
    27.         }
    28.     }
    29. }
    30.  
     
  2. JLF

    JLF

    Joined:
    Feb 25, 2013
    Posts:
    137
    I think the issue is that you’re using find object of type to get a reference to the audio source.

    Find object of type searches the whole scene but there’s no guarantee which object will be returned. So what I think is happening here is that the music player is using the same audio source as the sound effects.

    if you want to use this script to get an audio source on the same object try get component instead (I wrote an article on this that may help here: https://gamedevbeginner.com/how-to-...-script-in-unity-the-right-way/#get_component)