Facebook
From Fiery Giraffe, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 224
  1. using UnityEngine.Audio;
  2. using System;
  3. using UnityEngine;
  4.  
  5. public class AudioManager : MonoBehaviour
  6. {
  7.  
  8.     public Sound[] sounds;
  9.    
  10.  
  11.     void Awake()
  12.     {
  13.         // populate array attributes from sound source attributes
  14.         foreach (Sound s in sounds)
  15.            
  16.         {
  17.             s.source = gameObject.AddComponent<AudioSource>();
  18.             s.source.clip = s.clip;
  19.  
  20.             s.source.volume = s.volume;
  21.             s.source.pitch = s.pitch;
  22.            
  23.         }
  24.     }
  25.  
  26.     private void Start()
  27.     {
  28.         Play("Theme");
  29.        
  30.     }
  31.  
  32.  
  33.     public void Play(string name)
  34.     {
  35.  
  36.  
  37.         // find sound in sounds array where Sound.name is equal to name
  38.         Sound s = Array.Find(sounds, sound => sound.name == name);
  39.  
  40.         if (s == null)
  41.         {
  42.             // display sound not found error message
  43.             Debug.LogWarning("[Warning] " + name + " sound not found");
  44.             // don't execute
  45.             return;
  46.            
  47.         }
  48.         s.source.Play();
  49.     }
  50.  
  51. }
  52.