using System.Collections; using System.Collections.Generic; using System.Linq; using PixelCrushers; // For Saver using Sirenix.OdinInspector; // For ReadOnly/Button attributes (Optional: remove if not using Odin) using UnityEngine; using Random = UnityEngine.Random; namespace Beyond // Ensure this namespace matches your project { [RequireComponent(typeof(Collider))] public class BarkPlayer : Saver { #region Inspector Fields [Header("Bark Configuration")] [Tooltip("The indices of the BarkEntries in BarkManager's list to play sequentially.")] public int[] barkManagerEntryIndices = new int[0]; [Tooltip("Delay in seconds after one bark's audio finishes before starting the next bark WITHIN THE SAME entry sequence.")] [Min(0f)] public float delayBetweenBarks = 0.5f; [Tooltip("Delay in seconds after ALL barks in one entry sequence finish before starting the NEXT entry sequence.")] [Min(0f)] public float delayBetweenEntries = 5.0f; [Tooltip("Play barks within each entry in a random order (shuffled when the entry starts).")] public bool shuffleOrder = false; [Header("Trigger Settings")] [Tooltip("Layers that can activate this bark trigger.")] public LayerMask triggeringLayers; [Header("Activation")] [Tooltip("If true, the BarkPlayer will be active automatically when the game starts or when loaded without existing save data for it.")] public bool startAutomaticallyOnLoad = false; // Runtime state fields remain private but visible for debugging if needed [Header("Runtime State (Read Only)")] [SerializeField, ReadOnly] // Use Sirenix ReadOnly or remove if not using Odin private bool _runtime_IsStarted = false; // Tracks the current operational state [SerializeField, ReadOnly] private int currentEntryArrayIndex = 0; // Index for barkManagerEntryIndices array [SerializeField, ReadOnly] private int nextBarkSequenceIndex = 0; // Index for playbackOrder (within current entry) [SerializeField, ReadOnly] private bool isTriggeringObjectInside = false; // Is a valid object currently inside? #endregion #region Internal Variables private List playbackOrder; // Stores the bark order for the CURRENTLY active entry private bool isInitialized = false; private Collider triggerCollider; private BarkManager barkManager; // Cached reference private Coroutine currentPlaybackCoroutine = null; private Transform currentTriggererTransform = null; // Transform of the object inside #endregion #region Save Data Structure [System.Serializable] public class BarkPlayerData { public bool savedIsStarted; // Tracks the saved state from _runtime_IsStarted public int savedCurrentEntryArrayIndex; public int savedNextBarkSequenceIndex; public bool wasShuffled; // Tracks shuffle setting at time of save } private BarkPlayerData m_saveData = new BarkPlayerData(); #endregion #region Unity Lifecycle Methods public override void Awake() { _runtime_IsStarted = startAutomaticallyOnLoad; base.Awake(); triggerCollider = GetComponent(); if (!triggerCollider.isTrigger) { Debug.LogWarning($"BarkPlayer on {gameObject.name}: Collider was not set to 'Is Trigger'. Forcing it.", this); triggerCollider.isTrigger = true; } if (triggeringLayers.value == 0) { int playerLayer = LayerMask.NameToLayer("Player"); if (playerLayer != -1) { triggeringLayers = LayerMask.GetMask("Player"); Debug.LogWarning($"BarkPlayer on {gameObject.name}: Triggering Layers not set in inspector, defaulting to 'Player' layer.", this); } else { Debug.LogError($"BarkPlayer ({gameObject.name}): Triggering Layers is not set in the inspector, and the default 'Player' layer was not found. This trigger will likely not activate.", this); } } } private void Start() { barkManager = BarkManager.Instance; if (barkManager == null) { Debug.LogError($"BarkPlayer ({gameObject.name}): Could not find BarkManager instance! Disabling component.", this); enabled = false; return; } currentEntryArrayIndex = Mathf.Clamp(m_saveData.savedCurrentEntryArrayIndex, 0, Mathf.Max(0, barkManagerEntryIndices.Length - 1)); if (barkManagerEntryIndices == null || barkManagerEntryIndices.Length == 0) { Debug.LogWarning($"BarkPlayer ({gameObject.name}): No Bark Manager Entry Indices provided. Disabling.", this); enabled = false; return; } for (int i = 0; i < barkManagerEntryIndices.Length; i++) { if (barkManagerEntryIndices[i] < 0 || barkManagerEntryIndices[i] >= barkManager.m_barks.Length) { Debug.LogError($"BarkPlayer ({gameObject.name}): Invalid Bark Manager Entry Index {barkManagerEntryIndices[i]} at array position {i}. Max index is {barkManager.m_barks.Length - 1}. Disabling.", this); enabled = false; return; } } isInitialized = true; CheckForAutoStartIfInside(); // Check immediately if conditions are met } private void OnDrawGizmos() { Collider col = GetComponent(); if (col != null) { Gizmos.color = isTriggeringObjectInside ? new Color(1f, 0.5f, 0.5f, 0.4f) : new Color(0.5f, 1f, 0.5f, 0.3f); if (col is BoxCollider box) Gizmos.DrawCube(transform.TransformPoint(box.center), Vector3.Scale(box.size, transform.lossyScale)); else if (col is SphereCollider sphere) Gizmos.DrawSphere(transform.TransformPoint(sphere.center), sphere.radius * MaxComponent(transform.lossyScale)); } } #endregion #region Trigger Handling private void OnTriggerEnter(Collider other) { // Only ignore if not initialized or component is disabled if (!isInitialized || !enabled) return; // --- Layer Check --- int otherLayer = other.gameObject.layer; if ((triggeringLayers.value & (1 << otherLayer)) == 0) { return; // Layer not in mask, ignore this trigger event } // --- Check if already processing an object --- // This prevents multiple triggering objects from interfering. Only the first one in matters. if (isTriggeringObjectInside && other.transform != currentTriggererTransform) { // If another object enters while one is already tracked, ignore the new one. // If it's the *same* object re-entering (somehow), this check might be too strict, // but standard OnTriggerEnter/Exit should handle one object at a time. return; } if (isTriggeringObjectInside) return; // Simplified: if already tracking one, ignore others. // --- Valid Trigger - Mark presence --- // We set these REGARDLESS of _runtime_IsStarted so state is correct when StartPlayer() is called Debug.Log($"BarkPlayer ({gameObject.name}): Triggering object '{other.name}' entered (tracking presence).", this); isTriggeringObjectInside = true; currentTriggererTransform = other.transform; // Store the transform for barking // --- Start Playback Coroutine if player is started and not already running --- // This handles the case where the player enters *after* StartPlayer() has been called if (_runtime_IsStarted && currentPlaybackCoroutine == null) { Debug.Log($"BarkPlayer ({gameObject.name}): Player is active. Starting playback loop due to new entry.", this); // Apply potentially loaded/saved array index before starting loop currentEntryArrayIndex = Mathf.Clamp(m_saveData.savedCurrentEntryArrayIndex, 0, Mathf.Max(0, barkManagerEntryIndices.Length - 1)); // nextBarkSequenceIndex will be set by PrepareEntrySequence inside the coroutine currentPlaybackCoroutine = StartCoroutine(ContinuousPlaybackLoop()); } // If !_runtime_IsStarted, isTriggeringObjectInside is now true, // and CheckForAutoStartIfInside() (called by StartPlayer()) will pick it up. } private void OnTriggerExit(Collider other) { if (!isInitialized || !enabled) return; int otherLayer = other.gameObject.layer; if ((triggeringLayers.value & (1 << otherLayer)) == 0) { return; } if (other.transform == currentTriggererTransform) { Debug.Log($"BarkPlayer ({gameObject.name}): Tracked triggering object '{other.name}' exited.", this); isTriggeringObjectInside = false; currentTriggererTransform = null; if (currentPlaybackCoroutine != null) { StopCoroutine(currentPlaybackCoroutine); currentPlaybackCoroutine = null; Debug.Log($"BarkPlayer ({gameObject.name}): Stopping playback loop due to exit.", this); } } } #endregion #region Playback Logic private bool PrepareEntrySequence(int entryIndexToPrepare) { if (barkManager == null) return false; int barkCount = barkManager.GetBarkCountInEntry(entryIndexToPrepare); if (barkCount <= 0) { Debug.LogWarning($"BarkPlayer ({gameObject.name}): BarkEntry {entryIndexToPrepare} (from array index {currentEntryArrayIndex}) has no barks. Skipping entry.", this); playbackOrder = new List(); nextBarkSequenceIndex = 0; return false; } playbackOrder = Enumerable.Range(0, barkCount).ToList(); if (shuffleOrder) { for (int i = playbackOrder.Count - 1; i > 0; i--) { int j = Random.Range(0, i + 1); (playbackOrder[i], playbackOrder[j]) = (playbackOrder[j], playbackOrder[i]); } } // Apply saved index ONLY if the loaded entry array index matches the current one // AND if the shuffle setting at time of save matches current. // If shuffle setting changed, it's safer to restart the entry. if (currentEntryArrayIndex == m_saveData.savedCurrentEntryArrayIndex && shuffleOrder == m_saveData.wasShuffled) { nextBarkSequenceIndex = Mathf.Clamp(m_saveData.savedNextBarkSequenceIndex, 0, playbackOrder.Count); } else { nextBarkSequenceIndex = 0; } // Clear the saved next bark index after applying it or deciding not to, // so it's not incorrectly reused if we loop back to this entry without saving/loading. // m_saveData.savedNextBarkSequenceIndex = 0; // Reconsider this - only clear on actual load/new entry start. return true; } private IEnumerator ContinuousPlaybackLoop() { Debug.Log($"BarkPlayer ({gameObject.name}): Starting playback loop.", this); if (barkManagerEntryIndices == null || barkManagerEntryIndices.Length == 0) { Debug.LogError($"BarkPlayer ({gameObject.name}): Cannot start loop, entry indices array is empty or null.", this); currentPlaybackCoroutine = null; yield break; } // Outer loop: Continues as long as a valid triggering object is inside AND player is started while (isTriggeringObjectInside && currentTriggererTransform != null && _runtime_IsStarted) // Added _runtime_IsStarted check here too { if (currentEntryArrayIndex >= barkManagerEntryIndices.Length) { currentEntryArrayIndex = 0; if (barkManagerEntryIndices.Length == 0) { Debug.LogError($"BarkPlayer ({gameObject.name}): Entry indices array became empty during loop?", this); currentPlaybackCoroutine = null; // Ensure it's cleared yield break; } } int currentManagerEntryIndex = barkManagerEntryIndices[currentEntryArrayIndex]; bool canPlayEntry = PrepareEntrySequence(currentManagerEntryIndex); if (!canPlayEntry) { currentEntryArrayIndex++; m_saveData.savedNextBarkSequenceIndex = 0; // Ensure next time this entry is loaded (if looping), it starts fresh yield return null; continue; } while (nextBarkSequenceIndex < playbackOrder.Count && isTriggeringObjectInside && currentTriggererTransform != null && _runtime_IsStarted) { while (barkManager.IsPlaying && isTriggeringObjectInside && _runtime_IsStarted) { yield return null; } if (!isTriggeringObjectInside || currentTriggererTransform == null || !_runtime_IsStarted) break; int barkIndexToPlay = playbackOrder[nextBarkSequenceIndex]; Debug.Log($"BarkPlayer ({gameObject.name}): Playing Bark {nextBarkSequenceIndex + 1}/{playbackOrder.Count} (Actual Index: {barkIndexToPlay}) from Entry {currentManagerEntryIndex}.", this); AudioClip playedClip = barkManager.PlayBark(currentManagerEntryIndex, currentTriggererTransform, barkIndexToPlay); nextBarkSequenceIndex++; float waitTime = delayBetweenBarks; if (playedClip != null) { waitTime += Mathf.Max(0f, playedClip.length); } if (waitTime > 0) { float timer = 0f; while (timer < waitTime && isTriggeringObjectInside && currentTriggererTransform != null && _runtime_IsStarted) { timer += Time.deltaTime; yield return null; } } else { yield return null; } if (!isTriggeringObjectInside || currentTriggererTransform == null || !_runtime_IsStarted) break; } if (isTriggeringObjectInside && currentTriggererTransform != null && _runtime_IsStarted) { Debug.Log($"BarkPlayer ({gameObject.name}): Finished sequence for Entry {currentManagerEntryIndex}.", this); currentEntryArrayIndex++; m_saveData.savedNextBarkSequenceIndex = 0; // Reset for next entry if (currentEntryArrayIndex >= barkManagerEntryIndices.Length) { Debug.Log($"BarkPlayer ({gameObject.name}): Finished all entries in the array. Looping back.", this); currentEntryArrayIndex = 0; } if (delayBetweenEntries > 0) { Debug.Log($"BarkPlayer ({gameObject.name}): Waiting {delayBetweenEntries}s before next entry.", this); float timer = 0f; while (timer < delayBetweenEntries && isTriggeringObjectInside && currentTriggererTransform != null && _runtime_IsStarted) { timer += Time.deltaTime; yield return null; } if (!isTriggeringObjectInside || currentTriggererTransform == null || !_runtime_IsStarted) break; } } } Debug.Log($"BarkPlayer ({gameObject.name}): Playback loop finished.", this); // Only clear if this instance of the coroutine is the one stopping. // If StopPlayer() was called, it would have already nulled currentPlaybackCoroutine. if (currentPlaybackCoroutine == this.currentPlaybackCoroutine) // Check if this is still the active coroutine { currentPlaybackCoroutine = null; } } #endregion #region Public Control Methods [Button] public void StartPlayer() { if (!_runtime_IsStarted) { Debug.Log($"BarkPlayer ({gameObject.name}): Player Runtime Explicitly Started.", this); _runtime_IsStarted = true; // Clear any previously saved next bark index when explicitly starting, // unless shuffle settings are the same and we are on the same entry. // This is tricky. For now, CheckForAutoStartIfInside will rely on PrepareEntrySequence // to correctly determine if it should resume. // m_saveData.savedNextBarkSequenceIndex = 0; // Maybe too aggressive. if (isInitialized) { CheckForAutoStartIfInside(); } } else { Debug.Log($"BarkPlayer ({gameObject.name}): Player Runtime was already started.", this); } } [Button] public void StopPlayer() { if (_runtime_IsStarted) { Debug.Log($"BarkPlayer ({gameObject.name}): Player Runtime Explicitly Stopped.", this); _runtime_IsStarted = false; if (currentPlaybackCoroutine != null) { StopCoroutine(currentPlaybackCoroutine); currentPlaybackCoroutine = null; Debug.Log($"BarkPlayer ({gameObject.name}): Stopping active playback loop due to StopPlayer call.", this); } } } private void CheckForAutoStartIfInside() { // This is called from Start() and StartPlayer() if (_runtime_IsStarted && isTriggeringObjectInside && currentTriggererTransform != null && currentPlaybackCoroutine == null && isInitialized) { Debug.Log($"BarkPlayer ({gameObject.name}): Conditions met for auto-start. Object inside, player started, no active coroutine. Starting playback loop.", this); // Ensure currentEntryArrayIndex is correctly set from save data before starting // (it should already be from Start() or ApplyData(), but good to be sure) currentEntryArrayIndex = Mathf.Clamp(m_saveData.savedCurrentEntryArrayIndex, 0, Mathf.Max(0, barkManagerEntryIndices.Length - 1)); // nextBarkSequenceIndex will be determined by PrepareEntrySequence currentPlaybackCoroutine = StartCoroutine(ContinuousPlaybackLoop()); } } #endregion #region Save System Integration (Pixel Crushers Saver) public override string RecordData() { m_saveData.savedIsStarted = this._runtime_IsStarted; m_saveData.savedCurrentEntryArrayIndex = this.currentEntryArrayIndex; // Only save nextBarkSequenceIndex if a coroutine is running and we are "mid-sequence" // Otherwise, it should be 0 for the next entry. if (currentPlaybackCoroutine != null && nextBarkSequenceIndex > 0 && nextBarkSequenceIndex < (playbackOrder?.Count ?? 0)) { m_saveData.savedNextBarkSequenceIndex = this.nextBarkSequenceIndex; } else { // If not actively playing a sequence or at the start/end, save 0. // This means when loading, it will either start the currentEntryArrayIndex from the beginning, // or if currentEntryArrayIndex was incremented after an entry finished, it will start the *new* entry from beginning. m_saveData.savedNextBarkSequenceIndex = 0; } m_saveData.wasShuffled = this.shuffleOrder; return SaveSystem.Serialize(m_saveData); } public override void ApplyData(string s) { if (string.IsNullOrEmpty(s)) { _runtime_IsStarted = startAutomaticallyOnLoad; m_saveData = new BarkPlayerData(); // Ensure fresh save data container m_saveData.savedIsStarted = _runtime_IsStarted; // Sync with runtime m_saveData.savedCurrentEntryArrayIndex = 0; m_saveData.savedNextBarkSequenceIndex = 0; m_saveData.wasShuffled = shuffleOrder; // Use current inspector setting Debug.Log($"BarkPlayer ({gameObject.name}): No save data, using startAutomaticallyOnLoad ({_runtime_IsStarted}).", this); return; } var loadedData = SaveSystem.Deserialize(s); if (loadedData != null) { m_saveData = loadedData; this._runtime_IsStarted = m_saveData.savedIsStarted; // currentEntryArrayIndex and nextBarkSequenceIndex will be used by Start() and PrepareEntrySequence() Debug.Log($"BarkPlayer ({gameObject.name}): Applied loaded data. Started={_runtime_IsStarted}, EntryIdx={m_saveData.savedCurrentEntryArrayIndex}, BarkIdx={m_saveData.savedNextBarkSequenceIndex}, WasShuffled={m_saveData.wasShuffled}.", this); } else { Debug.LogError($"BarkPlayer ({gameObject.name}): Failed to deserialize save data. Using defaults.", this); _runtime_IsStarted = startAutomaticallyOnLoad; m_saveData = new BarkPlayerData(); m_saveData.savedIsStarted = _runtime_IsStarted; m_saveData.savedCurrentEntryArrayIndex = 0; m_saveData.savedNextBarkSequenceIndex = 0; m_saveData.wasShuffled = shuffleOrder; } // After applying data, if loaded state is 'stopped', ensure coroutine is also stopped. // CheckForAutoStartIfInside in Start() will handle restarting if needed. if (!this._runtime_IsStarted && currentPlaybackCoroutine != null) { StopCoroutine(currentPlaybackCoroutine); currentPlaybackCoroutine = null; } } #endregion #region Helper Methods private float MaxComponent(Vector3 v) => Mathf.Max(Mathf.Max(v.x, v.y), v.z); #endregion } }