x


How to play multiple audioclips from the same object?

I have a spaceship object and I want to play ambient sound, engine sounds and weapon sounds from the same object. But so far I only could add empty game objects to the spaceship and setting each one as audio source and play the sounds that way.

Is there an easy way to do it without creating multiple child objects?

more ▼

asked Apr 15 '12 at 05:22 PM

crocodile5 gravatar image

crocodile5
51 4 8 10

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

You can attach several AudioSources to the same object in the Inspector, and get them in an array at Awake with GetComponents(AudioSource) - but knowing who's who may become a problem, since there's no component identifier.
A better alternative is to add the AudioSources at Awake - the script SoundController.js in the Car Tutorial adds as many as 10 AudioSource components to the car!
You could do something like this:

// define the audio clips:
var clipAmb: AudioClip;
var clipEngine: AudioClip;
var clipWeapon1: AudioClip;
var clipWeapon2: AudioClip;

private var audioAmb: AudioSource;
private var audioEngine: AudioSource;
private var audioWeapon1: AudioSource;
private var audioWeapon2: AudioSource;

function AddAudio(clip:AudioClip, loop: boolean, playAwake: boolean, vol: float): AudioSource {
  var newAudio = gameObject.AddComponent(AudioSource);
  newAudio.clip = clip;
  newAudio.loop = loop;
  newAudio.playOnAwake = playAwake;
  newAudio.volume = vol;
  return newAudio;
}

function Awake(){
  // add the necessary AudioSources:
  audioAmb = AddAudio(clipAmb, true, true, 0.2);
  audioEngine = AddAudio(clipEngine, true, true, 0.4);
  audioWeapon1 = AddAudio(clipWeapon1, false, false, 0.8);
  audioWeapon2 = AddAudio(clipWeapon2, false, false, 0.8);
}

You can then use the audio sources like this:

  audioWeapon1.Play();
  audioEngine.pitch *= curVelocity/maxVelocity;
more ▼

answered Apr 15 '12 at 05:46 PM

aldonaletto gravatar image

aldonaletto
41.4k 16 42 197

Thanks that worked very well

Apr 15 '12 at 05:50 PM crocodile5
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x1027
x171
x29

asked: Apr 15 '12 at 05:22 PM

Seen: 2899 times

Last Updated: Apr 15 '12 at 05:50 PM