Files
match3-unity/Assets/Scripts/Services/AudioService.cs

43 lines
1.2 KiB
C#

using System;
using Services.Interfaces;
using UnityEngine;
using VContainer.Unity;
namespace Services
{
public sealed class AudioService : IAudioService, IInitializable, IDisposable
{
private readonly float volume = 1f;
private GameObject gameObject;
private AudioSource source;
public void Initialize()
{
this.gameObject = new GameObject("AudioService");
UnityEngine.Object.DontDestroyOnLoad(this.gameObject);
this.source = this.gameObject.AddComponent<AudioSource>();
this.source.playOnAwake = false;
this.source.loop = false;
this.source.volume = this.volume;
}
public void PlaySound(AudioClip clip)
{
if (clip == null) return;
if (this.source == null) return; // In case it's called before Initialize in some edge setup
this.source.PlayOneShot(clip);
}
public void Dispose()
{
if (this.gameObject != null)
{
UnityEngine.Object.Destroy(this.gameObject);
this.gameObject = null;
this.source = null;
}
}
}
}