Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sydney4529
Created April 9, 2018 01:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sydney4529/47f05638b74c6928fb4c7385e7eb3c64 to your computer and use it in GitHub Desktop.
Save sydney4529/47f05638b74c6928fb4c7385e7eb3c64 to your computer and use it in GitHub Desktop.
Audio manager for the sound in the game
using UnityEngine.Audio;
using System;
using UnityEngine;
//Credit to Brackeys youtube tutorial on Audio managers, as the majority of this code and learning how to use it was made by him.
public partial class SAudioManager : MonoBehaviour
{
public Sound[] sounds;
public static SAudioManager instance;
//AudioManager
void Awake()
{
if (instance == null)
instance = this;
else
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
foreach (Sound s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.pitch = s.pitch;
s.source.loop = s.loop;
}
}
void Start()
{
Play("Theme");
}
public void Play(string name)
{
Sound s = Array.Find(sounds, sound => sound.name == name);
if (s == null)
{
Debug.LogWarning("Sound: " + name + " not found");
return;
}
s.source.Play();
}
//this addition to the code was made by me, the rest was from Brackeys tutorial
public void Stop(string name)
{
Sound s = Array.Find(sounds, sound => sound.name == name);
s.source.Stop();
}
}
@zorah11
Copy link

zorah11 commented Nov 27, 2021

How thanks I was looking for this

@ujuj04
Copy link

ujuj04 commented Jun 11, 2023

Thanks!

@NielsH12
Copy link

You should add the same null check in stop

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment