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. Dismiss Notice

Assign audioclips to audio source in a script

Discussion in 'Scripting' started by champenoise, Sep 13, 2014.

  1. champenoise

    champenoise

    Joined:
    Sep 4, 2014
    Posts:
    2
    I want to set which of two audioclips is played in a script. Code snippets showing how to do this don't seem to work. I must be getting something basic wrong. In this one from Unity documentation I presume that one clip is assigned in the inspector, it gets played and then a clip called "otherClip" gets assigned and played.

    My audio files are "Boo_trunc.wav" and "Weh_trunc.wav", they are under "Assets" and they both play okay when I click on them. It looks like Unity refers to them without extension. My script is named "NewBehaviourScript". I assigned Boo_trunc to the audio source in the inspector.

    using UnityEngine;
    using System.Collections;

    [RequireComponent(typeof(AudioSource))]
    public class NewBehaviourScript : MonoBehaviour {
    public AudioClip Weh_trunc;
    IEnumerator Start() {
    audio.Play ();
    yield return new WaitForSeconds (audio.clip.length);
    audio.clip = Weh_trunc;
    audio.Play ();
    }
    }

    When I run it, Boo_trunc plays, and then it is removed from audio source in the inspector. Weh_trunc does not play and is listed under the script component. Probably something glaringly obvious to the experienced user. Please let me know if you have any idea, thanks!
     
  2. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    238
    Works fine for me! :3 Are you sure you're assigning Weh_trunc to the right place? (by dragging it onto the Weh_trunc field in the inspector) sorry if I am sending you in circles through things you've already checked, just making sure. It works for me! :S
     
  3. champenoise

    champenoise

    Joined:
    Sep 4, 2014
    Posts:
    2
    That's it! Thanks, I really had no idea.