Search Unity

Assign audio clip via scripting to an object

Discussion in 'Scripting' started by Selene, Jun 10, 2011.

  1. Selene

    Selene

    Joined:
    Mar 2, 2011
    Posts:
    25
    Hello,

    I was searching the forums for an answer, but couldn't find anything so far. What I am trying to do is to assign an audio clip to an object during runtime.
    I couldn't find anything which would say how can this be done.
    Here's my script so far:
    Code (csharp):
    1.  
    2. var object1 : GameObject;
    3. var sound_name : AudioClip;
    4.  
    5. function Start(){
    6.    
    7.     object1 = gameObject.Find("object1");
    8.     object1.AddComponent(AudioSource);
    9.     audio.clip = Resources.Load(sound_name);
    10.    
    11. }
    Unfortunately this only adds the audio source component to the object but the audio clip will be null.
    Any ideas?

    Thanks in advance.
     
  2. orb_9

    orb_9

    Joined:
    Feb 10, 2010
    Posts:
    47
    Untested, but should do the trick:

    Code (csharp):
    1.  
    2. function Start(){
    3.    
    4.     object1 = gameObject.Find("object1");
    5.     audioSource = object1.AddComponent(AudioSource);
    6.     audioSource.clip = Resources.Load(sound_name);
    7. }
    8.  
    If this still does not work, the resource cannot be loaded (for whatever reason).
     
  3. Selene

    Selene

    Joined:
    Mar 2, 2011
    Posts:
    25
    Thanks really much, this worked pretty well :)