Merge branch 'main' of https://homelab.tailf7f81b.ts.net/tschesky/AppleHillsProduction
This commit is contained in:
@@ -1,22 +1,80 @@
|
||||
using UnityEngine;
|
||||
using UnityEngine.Audio;
|
||||
using System;
|
||||
using Core.Lifecycle;
|
||||
|
||||
public class LevelAudioObject : MonoBehaviour
|
||||
[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;
|
||||
|
||||
// Start is called once before the first execution of Update after the MonoBehaviour is created
|
||||
void Start()
|
||||
private bool _hasPlayed;
|
||||
|
||||
#region ManagedBehaviour Overrides
|
||||
|
||||
public override bool AutoRegisterForSave => isOneTime; // Only save if one-time audio
|
||||
|
||||
protected override string OnSceneSaveRequested()
|
||||
{
|
||||
PlayNarrationAudio();
|
||||
if (!isOneTime)
|
||||
return null; // No need to save if not one-time
|
||||
|
||||
LevelAudioObjectSaveData saveData = new LevelAudioObjectSaveData
|
||||
{
|
||||
hasPlayed = _hasPlayed
|
||||
};
|
||||
|
||||
return JsonUtility.ToJson(saveData);
|
||||
}
|
||||
|
||||
void PlayNarrationAudio()
|
||||
protected override void OnSceneRestoreRequested(string serializedData)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
narratorAudioSource.audioSource.resource = firstNarration;
|
||||
narratorAudioSource.Play(0);
|
||||
|
||||
_hasPlayed = true;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user