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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Choosing AudioSource Component from script

Discussion in 'Scripting' started by iDavisSK, Jan 23, 2021.

  1. iDavisSK

    iDavisSK

    Joined:
    Sep 29, 2020
    Posts:
    2
    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)?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    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.
     
  3. iDavisSK

    iDavisSK

    Joined:
    Sep 29, 2020
    Posts:
    2
    Seems like I'm not able to drag the audio into that slot. Is there some required format of audio? I use .mp3.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,780
    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.
     
    iDavisSK likes this.