0
\$\begingroup\$

I am not able to play my audio source if I deactivate the panel where the AudioSource is attached to AFTER it.

    _audioBtnEnter = tmpBtnGeneral.GetComponent<AudioSource>();       
    _audioBtnEnter.Play();
    tmpBtnGeneral.SetActive(false);

I would totaly understand if this would not be possible:

    tmpBtnGeneral.SetActive(false);
    _audioBtnEnter.Play();

But why does the first code not trigger the audio play?

Is this a race condition problem?

\$\endgroup\$
3
\$\begingroup\$

When disabling a gameobject, all the attached components are disabled too.

Documentation states the following :

Making a GameObject inactive will disable every component, turning off any attached renderers, colliders, rigidbodies, scripts, etc... Any scripts that you have attached to the GameObject will no longer have Update() called, for example."

Since your audio source is attached to your gameobject, disabling the gameobject (and thus, the component) will stop the audiosource from playing your audio.

If you need to hide the gameobject, you could disable the Renderer instead of the gameobject itself. Otherwise, create an empty gameobject holding your audiosource and disable the gameobject.

\$\endgroup\$
  • \$\begingroup\$ I know, but I am first playing the audio and then disabling the panel. I think the audio play starts but gets interrupted as soon as the gameObject is removed. I think I have to solve this by using a coroutine. I just wanted to add a sound to a menue button which is played as soon as it gets clicked. \$\endgroup\$ – Black Nov 1 '17 at 11:11
  • 1
    \$\begingroup\$ An audio file can't be played "on its own" (without an active audiosource) \$\endgroup\$ – Hellium Nov 1 '17 at 11:12
  • 1
    \$\begingroup\$ @Black : You should accept your answer instead of mine ;) \$\endgroup\$ – Hellium Nov 1 '17 at 11:44
0
\$\begingroup\$

I solved it by adding an AudioSource Component to the gameObject where my script is attached to and adding a reference to my audio file in the script. Then I play it like this.

public AudioClip audioBtnEnter; //Reference to Audio Clip

...

this.gameObject.GetComponent<AudioSource>().PlayOneShot(_audioBtnEnter);
tmpBtnGeneral.SetActive(false);
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.