SerializerWorldItem.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using Sirenix.OdinInspector;
  5. using KairoEngine.Core;
  6. using KairoEngine.Inventory;
  7. namespace KairoEngine.CharacterSystem
  8. {
  9. public class SerializerWorldItem : MonoBehaviour
  10. {
  11. [HideInInspector] public bool loadedFromData = false;
  12. private WorldItem worldItem;
  13. void Start()
  14. {
  15. worldItem = gameObject.GetComponent<WorldItem>();
  16. if(worldItem == null) Debug.LogError("No WorldItem found for SerializeWorldItem in GameObject " + gameObject.name);
  17. ItemBase item = ItemLibrary.GetItemByName(worldItem.itemName);
  18. if(item.category == ItemType.firearm || item.category == ItemType.handWeapon)
  19. {
  20. // Don't destroy this object if its in the hand of a character
  21. Firearm firearm = gameObject.GetComponent<Firearm>();
  22. if(firearm == null) return;
  23. if(firearm.character != null) return;
  24. }
  25. if(DataManager.instance == null) return;
  26. if(DataManager.instance.currentSceneData.visited > 1 && loadedFromData == false)
  27. {
  28. Destroy(gameObject);
  29. }
  30. }
  31. void OnEnable()
  32. {
  33. SerializationEvents.OnSerializeData += Serialize;
  34. }
  35. void OnDisable()
  36. {
  37. SerializationEvents.OnSerializeData -= Serialize;
  38. }
  39. private void Serialize()
  40. {
  41. Firearm firearm = gameObject.GetComponent<Firearm>();
  42. if(firearm != null)
  43. {
  44. // Don't serialzie this object if its in the hand of a character
  45. if(firearm.character != null) return;
  46. }
  47. string name = worldItem.itemName;
  48. int quantity = worldItem.quantity;
  49. string ammoName = worldItem.itemAmmoName;
  50. int ammo = worldItem.ammoQuantity;
  51. float lastUsed = worldItem.lastUsed;
  52. Vector3 position = transform.position;
  53. Quaternion rotation = transform.rotation;
  54. DataWorldItem dataWorldItem = new DataWorldItem(name, quantity, position, rotation, ammoName, ammo, lastUsed);
  55. DataManager.instance.currentSceneData.worldItemsData.Add(dataWorldItem);
  56. }
  57. }
  58. }