Choosing AudioSource Component from script

Hey, I have a game object (player), that holds 2 audio source components - one of them is for collecting money, the other is for losing the game. I have a script, which determines the action performed by a player and want to play the specific sound, based on the action. How can I distinguish, in the script, which component I want to use (so which specific audio I want to play)?

Make two public AudioSource variables, one for each, and drag the correct one into each slot.

When you’re looking at an object in the inspector, you can drag individual components into individual slots. You can also lock the inspector window (tiny lock upper right) to select other stuff and not have the inspector change. Or even open multiple inspector windows and lock one of them, etc.

Seems like I’m not able to drag the audio into that slot. Is there some required format of audio? I use .mp3.

First you need to understand some differences here:

AudioSource: a component that goes on a GameObject and will play an AudioClip

AudioClip: an asset (usually on disk) that can be played by an AudioSource.

There is also a static method in AudioSource to one-shot-play a sound.

Your original post asked about AudioSources. Your subsequent post is talking about AudioClips.

If you select an AudioClip (your MP3) in the project and the bottom of the inspector window doesn’t have a waveform and a play arrow in it, that MP3 file did not import.

1 Like