HELP! Audio Source Problem

i want access AudioSource from other object

  1. MainObject

    var audio: AudioClip;

    @script RequireComponent.getComponent(AudioSource)

    function Update(){

    audio.Play(); 
    

    }

  2. Sub Object (how to access AudioSource from main object)

    var audioSource: AudioSource; //i put the main object here

     var myAudio: AudioClip;
     
     function Update(){    
     
         audio.Play(); //doesn't work    
     
     }
    

NB: sorry for my bad english

Does your first script even compile? I think if you use JavaScript you should write:

@script RequireComponent(AudioSource)

instead of

@script RequireComponent.getComponent(AudioSource)

It’s also probably a bad idea to play the audio in the Update() function as this will restart your audio every frame and you won’t hear anything. For testing you should better write it into the Start() function so it’s only played once.
I think you also get an error or a warning if you name a variable “audio”.


As you wrote you want to access the AudioSource from another object, the first script is not necessary in this case. All you have to do is to add an AudioSource to the main object. Then in the script for the sub/child object, you need to assign the audio file to the AudioSource and then play the file. Check this script:

#pragma strict

var audioSource : AudioSource; // Reference to the AudioSource
var myAudio : AudioClip; // The clip you want to play
 
function Start() {
	audioSource.audio.clip = myAudio; // Assigns your clip to the AudioSource
	audioSource.audio.Play(); // Plays the clip assigned to the AudioSource
}

There are also other ways to play the audio, for example using the PlayOneShot() function:

#pragma strict

var audioSource : AudioSource;
var myAudio : AudioClip;
 
function Start(){
	audioSource.audio.PlayOneShot( myAudio );
}