Why I have to keep an AudioSource into Hierarchy in order to work?

I have an AudioClip attached to an AudioSource and it makes a Prefab.

The prefabs are into an array by the player.

public GameObject[] BancoDeSonidos;

If I want it to Play, I get: “Can not play a disabled audio source” but if I stand the prefab in the hierarchy, it works like a charm.

BancoDeSonidos[0].GetComponent<AudioSource>().Play();

Why?

I would like enable it by scripting, but if I type like

            if (!this.BancoDeSonidos[0].GetComponent<AudioSource>().isPlaying)
            {
                if (!this.BancoDeSonidos[0].GetComponent<AudioSource>().enabled==true)
                    BancoDeSonidos[0].GetComponent<AudioSource>().Play();
            }

I get same, “Can not play a disabled audio source”. So, I don’t understand it.
Why does it execute Play() if it is not enabled?

It makes me crazy -.-

Thank you.

Green arrow: working.
Red arrow: not working.

Objects must be in the scene to work. You can’t play an audiosource on a prefab that hasn’t been instantiated into a scene, because it’s “nowhere” and can’t do anything.

–Eric

2 Likes

This. Prefabs aren’t real GameObjects. They are just a set of text data that tells Unity how to build a real GameObject.

They are a blueprint if you like. You can use blueprints for lots of things. You can even make a full building form them. But standing on the elevator in the blueprint isn’t going to get you off the ground.

1 Like

Thank you very much both. That is basic to know -.-’

If you just want to play a sound at some position in the world and don’t want to worry about having a GameObject there then you can use this: Unity - Scripting API: AudioSource.PlayClipAtPoint

1 Like

Thank you very much. It is another option. In fact, I would like to attach all the sounds that the player can make in a its GameObject. I don´t like the hierarchy’s visual full with audios. It sees out like there’s not organization.

Another option is an empty static GameObject managing the sounds, but, I don’t want to use it so far.

All you need is a single AudioSource component; you don’t need a different GameObject for each sound.

–Eric

1 Like