Add: Generic loopable sound + playlist

This commit is contained in:
Banane_Rotative
2026-01-18 17:43:13 +01:00
parent e03d925573
commit 8067bb5247
8 changed files with 118 additions and 2 deletions

View File

@@ -89,7 +89,7 @@ AudioSource:
m_Curve:
- serializedVersion: 3
time: 0
value: 0
value: 1
inSlope: 0
outSlope: 0
tangentMode: 0

View File

@@ -0,0 +1,48 @@
using UnityEngine;
public abstract class ILoopableSound : MonoBehaviour
{
protected AudioSource source;
protected void CreateSource()
{
source = Instantiate(SoundManager.Instance.audioSourcePrefab).GetComponent<AudioSource>();
source.loop = true;
}
protected void DestroySource()
{
if (source != null)
{
Destroy(source.gameObject);
}
}
protected void OnDestroy()
{
DestroySource();
}
public void PlayLoopableSound(Vector3 position)
{
CreateSource();
source.transform.position = position;
PlayLoopableSound();
}
public void PlayLoopableSound(Transform parent)
{
CreateSource();
source.transform.SetParent(parent, false);
PlayLoopableSound();
}
protected virtual void PlayLoopableSound() { }
protected virtual void StopLoopableSound()
{
DestroySource();
}
public bool IsPlaying { get { return source != null; } }
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a71883758609f8342858a3b5c4c641d8

View File

@@ -0,0 +1,43 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LoopablePlaylist : ILoopableSound
{
[SerializeField] List<AudioClip> playlist;
Coroutine playlistCoroutine = null;
protected override void PlayLoopableSound()
{
base.PlayLoopableSound();
if (playlist.Count == 0)
{
Debug.LogWarning("Playlist is empty");
return;
}
source.loop = false;
playlistCoroutine = StartCoroutine(PlaylistCoroutine());
source.clip = playlist[0];
source.Play();
}
protected override void StopLoopableSound()
{
StopCoroutine(playlistCoroutine);
source.Stop();
base.StopLoopableSound();
}
protected IEnumerator PlaylistCoroutine()
{
int playlistIndex = 0;
while (true)
{
source.clip = playlist[playlistIndex];
source.Play();
yield return new WaitForSeconds(playlist[playlistIndex].length);
playlistIndex = (playlistIndex + 1) % playlist.Count;
}
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 914bb056e791dc74491ef6034c2a70dd

View File

@@ -0,0 +1,19 @@
using UnityEngine;
public class LoopableSound : ILoopableSound
{
[SerializeField] AudioClip sound;
protected override void PlayLoopableSound()
{
base.PlayLoopableSound();
source.clip = sound;
source.Play();
}
protected override void StopLoopableSound()
{
source.Stop();
base.StopLoopableSound();
}
}

View File

@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 287885c28387db147b2ed37b247e9fc2

View File

@@ -11,7 +11,7 @@ using UnityEngine;
public class SoundManager : MonoBehaviour
{
[SerializeField] private int initialPoolSize = 10;
[SerializeField] private GameObject audioSourcePrefab;
[SerializeField] public GameObject audioSourcePrefab;
private List<AudioSource> audioPool;
private Queue<AudioSource> availableAudios;