Add Audio
This commit is contained in:
43
Assets/Scripts/Services/AudioService.cs
Normal file
43
Assets/Scripts/Services/AudioService.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
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 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user