Play sound using other objects

I am trying to play a sound in the other object and I don’t know why it’s not working. I have this code:

    public Player thePlayer;
    public Ball theBall;
  
    void Update () {
      
            if (player.won) {
                thePlayer.GetComponent<AudioSource>().Play ();
            } else {
                theBall.GetComponent<AudioSource>().Play ();
            }

    }

Can you elaborate on “it’s not working”? Are you getting any errors? Or no errors, just nothing plays?

Is there an audio clip loaded for each object? Have you set up “thePlayer” and “theBall” references in the inspector? (i.e. drag these objects in via property inspector)

I am getting no errors but the sounds are not playing. The references are okay.

Sorry, but I did not understand about the “audio clip loaded for each object” you asked. Could you give me more details about this?

In order for your Audio Source to know what to play, it has to have an audio clip loaded somewhere. An “audio clip” is a sound file. Put another way… if you don’t tell your source what to play, how can it play anything?

See this doc here:

The audio clip is the first thing listed on the Audio Source. (Or you can load an audio clip via code)

I have inserted an audio clip once I included the component . Including I tested each audio clip enabling the “Play on awake” option.

My next thought here is that you have it playing every frame without checking if it’s already playing, so I think it’s interrupting itself. Check to make sure it’s not already playing first, or figure out a way to do it so that it doesn’t keep replaying every frame.

When you call “Play” it will stop whatever is playing on that audio source and play the clip you provide… so in this case, I think it just keeps restarting every frame.

1 Like

You are right! I created a function to play de audio clips and now the sound worked.

Thanks for you time. You really helped me.

No problem, glad I could help!