Files
AppleHillsProduction/Assets/Scripts/Sound/LevelAudioObject.cs

81 lines
2.0 KiB
C#
Raw Normal View History

2025-10-17 14:38:42 +02:00
using UnityEngine;
using UnityEngine.Audio;
using System;
2025-11-10 11:09:06 +01:00
using Core.Lifecycle;
2025-10-17 14:38:42 +02:00
2025-11-10 11:09:06 +01:00
[Serializable]
public class LevelAudioObjectSaveData
2025-10-17 14:38:42 +02:00
{
2025-11-10 11:09:06 +01:00
public bool hasPlayed;
}
public class LevelAudioObject : ManagedBehaviour
{
[Header("Audio Settings")]
2025-10-29 17:01:02 +01:00
public AppleAudioSource narratorAudioSource;
2025-10-17 14:38:42 +02:00
public AudioResource firstNarration;
2025-11-10 11:09:06 +01:00
[Header("Playback Settings")]
[Tooltip("If true, the audio will only play once and never again after being played")]
public bool isOneTime;
private bool _hasPlayed;
#region ManagedBehaviour Overrides
2025-10-17 14:38:42 +02:00
2025-11-10 11:09:06 +01:00
public override bool AutoRegisterForSave => isOneTime; // Only save if one-time audio
protected override string OnSceneSaveRequested()
2025-10-17 14:38:42 +02:00
{
2025-11-10 11:09:06 +01:00
if (!isOneTime)
return null; // No need to save if not one-time
LevelAudioObjectSaveData saveData = new LevelAudioObjectSaveData
{
hasPlayed = _hasPlayed
};
return JsonUtility.ToJson(saveData);
2025-10-17 14:38:42 +02:00
}
2025-11-10 11:09:06 +01:00
protected override void OnSceneRestoreRequested(string serializedData)
2025-10-17 14:38:42 +02:00
{
2025-11-10 11:09:06 +01:00
if (!isOneTime || string.IsNullOrEmpty(serializedData))
return;
try
{
LevelAudioObjectSaveData saveData = JsonUtility.FromJson<LevelAudioObjectSaveData>(serializedData);
_hasPlayed = saveData.hasPlayed;
}
catch (Exception e)
{
Debug.LogWarning($"[LevelAudioObject] Failed to restore audio state: {e.Message}");
}
}
protected override void OnSceneRestoreCompleted()
{
if (isOneTime && !_hasPlayed)
{
PlayNarrationAudio();
}
}
#endregion
private void PlayNarrationAudio()
{
if (narratorAudioSource == null || firstNarration == null)
{
Debug.LogWarning($"[LevelAudioObject] Missing audio source or narration resource on {gameObject.name}");
return;
}
2025-10-29 17:01:02 +01:00
narratorAudioSource.audioSource.resource = firstNarration;
2025-10-30 14:17:47 +01:00
narratorAudioSource.Play(0);
2025-11-10 11:09:06 +01:00
_hasPlayed = true;
2025-10-17 14:38:42 +02:00
}
}