using System; using System.Collections; using System.Collections.Generic; using PixelCrushers; using PixelCrushers.DialogueSystem; using UnityEngine; using UnityEngine.Events; namespace Beyond { public class NotifierSaveData { public List found = new(); public NotifierSaveData(List data) { found = data; } public NotifierSaveData() { found = new(); } } public class ItemNotifier : Saver { [Serializable] public class ItemEvent { public int itemId; public float delay = 0f; public bool onFirstCollection = true; public string barkMessage; public AudioClip clipToPlay; public UnityEvent onCollected; } public List m_itemsToCollect; private List m_itemFound = new(); private bItemManager m_itemManager; private AudioSource m_audioSource; public override void Awake() { base.Awake(); m_itemManager = GetComponent(); m_itemsToCollect.ForEach(item => m_itemFound.Add(false)); m_audioSource = GetComponent(); } //use one frame delay to ommit all item that are added on start private IEnumerator AddListenerWithDelay() { yield return new WaitForSeconds(1f); m_itemManager.onAddItem.AddListener(OnAddItem); m_itemManager.onChangeItemAmount.AddListener(OnAddItem); yield return null; } // Start is called before the first frame update public override void OnEnable() { base.OnEnable(); StartCoroutine(AddListenerWithDelay()); } public override void OnDisable() { base.OnDisable(); StopAllCoroutines(); m_itemManager.onAddItem.RemoveListener(OnAddItem); m_itemManager.onChangeItemAmount.RemoveListener(OnAddItem); } public override string RecordData() { NotifierSaveData data = new(m_itemFound); return JsonUtility.ToJson(data, true); } public override void ApplyData(string s) { NotifierSaveData data = new(); JsonUtility.FromJsonOverwrite(s, data); if (data.found != null && data.found.Count > 0) { m_itemFound = data.found; } } private IEnumerator ItemCoroutine(int i) { var it = m_itemsToCollect[i]; if (m_itemFound != null && i < m_itemFound.Count && m_itemFound[i] && it.onFirstCollection) { yield return null; } else { m_itemFound[i] = true; if (it.delay > 0f) yield return new WaitForSeconds(it.delay); if (!string.IsNullOrEmpty(it.barkMessage)) { DialogueManager.BarkString(it.barkMessage, Player.Instance.transform); } if (it.clipToPlay != null && m_audioSource != null) { m_audioSource.clip = it.clipToPlay; m_audioSource.Play(); } it.onCollected?.Invoke(); } } private void OnAddItem(bItem item) { for (int i = 0; i < m_itemsToCollect.Count; i++) { var it = m_itemsToCollect[i]; if (it.itemId == item.id) { StartCoroutine(ItemCoroutine(i)); } } } } }