82 lines
2.0 KiB
C#
82 lines
2.0 KiB
C#
using UnityEngine;
|
|
using UnityEngine.Audio;
|
|
using System;
|
|
using Core;
|
|
using Core.Lifecycle;
|
|
|
|
[Serializable]
|
|
public class LevelAudioObjectSaveData
|
|
{
|
|
public bool hasPlayed;
|
|
}
|
|
|
|
public class LevelAudioObject : ManagedBehaviour
|
|
{
|
|
[Header("Audio Settings")]
|
|
public AppleAudioSource narratorAudioSource;
|
|
public AudioResource firstNarration;
|
|
|
|
[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
|
|
|
|
public override bool AutoRegisterForSave => isOneTime; // Only save if one-time audio
|
|
|
|
internal override string OnSceneSaveRequested()
|
|
{
|
|
if (!isOneTime)
|
|
return null; // No need to save if not one-time
|
|
|
|
LevelAudioObjectSaveData saveData = new LevelAudioObjectSaveData
|
|
{
|
|
hasPlayed = _hasPlayed
|
|
};
|
|
|
|
return JsonUtility.ToJson(saveData);
|
|
}
|
|
|
|
internal override void OnSceneRestoreRequested(string serializedData)
|
|
{
|
|
if (!isOneTime || string.IsNullOrEmpty(serializedData))
|
|
return;
|
|
|
|
try
|
|
{
|
|
LevelAudioObjectSaveData saveData = JsonUtility.FromJson<LevelAudioObjectSaveData>(serializedData);
|
|
_hasPlayed = saveData.hasPlayed;
|
|
}
|
|
catch (Exception e)
|
|
{
|
|
Logging.Warning($"[LevelAudioObject] Failed to restore audio state: {e.Message}");
|
|
}
|
|
}
|
|
|
|
internal override void OnSceneRestoreCompleted()
|
|
{
|
|
if (isOneTime && !_hasPlayed)
|
|
{
|
|
PlayNarrationAudio();
|
|
}
|
|
}
|
|
|
|
#endregion
|
|
|
|
private void PlayNarrationAudio()
|
|
{
|
|
if (narratorAudioSource == null || firstNarration == null)
|
|
{
|
|
Logging.Warning($"[LevelAudioObject] Missing audio source or narration resource on {gameObject.name}");
|
|
return;
|
|
}
|
|
|
|
narratorAudioSource.audioSource.resource = firstNarration;
|
|
narratorAudioSource.Play(0);
|
|
|
|
_hasPlayed = true;
|
|
}
|
|
}
|