Search Unity

Randomizing Main Camera's audio source

Discussion in 'Scripting' started by mogambo, Jul 29, 2014.

  1. mogambo

    mogambo

    Joined:
    Oct 14, 2013
    Posts:
    42
    I'm working on integrating audio to my game. I'm playing sound by attaching sound to camera's audio source.

    But, I need to randomize the audio source of my camera. can some one please help me with this ?
    how should I manipulate this ?

    I'm currently using this:

    Code (CSharp):
    1. public class PlayRandomAudio : MonoBehaviour {
    2.  
    3.     public Camera MainCamera;
    4.  
    5.     public AudioClip[] sounds; // set the array size and fill the elements with the sounds
    6.    
    7.     void  PlayRandom ()
    8.    
    9.     { // call this function to play a random sound
    10.         AudioSource.Instantiate(MainCamera);
    11.         if (audio.isPlaying) return; // don't play a new sound while the last hasn't finished
    12.         audio.clip  = sounds[(int)Random.Range(0.0f,4.0f)];
    13.         MainCamera.audio.Play();
    14.  
    15.     }
    16. }
     
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    I've not "done" audio... but what is this line

    Code (csharp):
    1.  
    2. AudioSource.Instantiate(MainCamera);
    3.  
    meant to do? looks wrong...
     
  3. mogambo

    mogambo

    Joined:
    Oct 14, 2013
    Posts:
    42
    That was part of trail on if this is the reason for not playing.
    I achieved playing audio with this code.

    Code (CSharp):
    1. public class PlayRandomAudio : MonoBehaviour {
    2.  
    3.     public AudioClip[] sounds; // set the array size and fill the elements with the sounds
    4.    
    5.     void  Start ()
    6.    
    7.     {
    8.         audio.clip  = sounds[(int)Random.Range(0.0f,4.0f)];
    9.         audio.Play();
    10.     }
    11. }
    But, on second level, the game becomes damn slow.
    Any help here ?