Add Audio

This commit is contained in:
2025-12-17 01:46:24 +08:00
parent 3786863b00
commit 9f2ef833b2
12 changed files with 116 additions and 2 deletions

View 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;
}
}
}
}