using System; using System.Collections.Generic; using RPGCore.BackpackEquipment.Data; using RPGCore.BackpackEquipment.ObjectModules.Content.Events; using RPGCore.BackpackEquipment.Objects; using RPGCore.Core; using RPGCore.Core.Objects; using RPGCore.ObjectModules.EventObjectModule.Events; using UnityEngine; namespace RPGCore.BackpackEquipment.ObjectModules.Content { [Serializable] [ObjectModule( name: "[Inventory] Content", description: "Simple content managing attached to any implementation of BaseObject. " + "By itself allows only: taking, dropping and deciding who manages items. " + "Attach implementation of "+nameof(IContentOwner)+" to manage content's items." )] public sealed class ContentModule : ObjectModule { // RUNTIME private GameObject _contentGameObject; private Dictionary _items = new(); private void Awake() { _contentGameObject = new GameObject("-- CONTENT --"); _contentGameObject.transform.SetParent(transform); _contentGameObject.transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity); } public bool Take(ItemObject item) { if (item.data.Get().carriedBy) return false; if (_items.ContainsKey(item)) return false; _items.TryAdd(item, null); item.data.Get().carriedBy = parent; parent.events.Invoke(new ContentAddEvent{obj = parent, item = item}); item.events.Register(OnItemRemove); item.gameObject.SetActive(false); item.transform.SetParent(_contentGameObject.transform); item.transform.SetLocalPositionAndRotation(Vector3.zero, Quaternion.identity); return true; } public bool Drop(ItemObject item) { if (!_items.ContainsKey(item)) return false; _items[item]?.Remove_Internal(item); _items.Remove(item); item.data.Get().carriedBy = null; parent.events.Invoke(new ContentRemoveEvent { obj = parent, item = item }); item.events.Unregister(OnItemRemove); item.gameObject.SetActive(true); item.transform.SetParent(null); return true; } public bool TransferTo(IContentOwner newOwner, ItemObject item, int index = -1) { if (item.data.Get().carriedBy != parent) return false; if (!newOwner.CanAdd(item, index)) return false; _items.TryAdd(item, null); _items[item]?.Remove_Internal(item); _items[item] = newOwner; newOwner.Add_Internal(item, index); return true; } public bool TransferFrom(ItemObject item) { return _items[item]?.Remove_Internal(item) ?? false; } private void OnItemRemove(RemoveEvent removeEvent) { Drop(removeEvent.obj as ItemObject); } } }