First go around with save load system

This commit is contained in:
Michal Pikulski
2025-11-02 12:48:48 +01:00
parent 5d6d4c8ba1
commit ebca297d28
13 changed files with 1511 additions and 122 deletions

View File

@@ -16,6 +16,19 @@ namespace Interactions
Forbidden
}
/// <summary>
/// Saveable data for ItemSlot state
/// </summary>
[System.Serializable]
public class ItemSlotSaveData
{
public PickupSaveData pickupData; // Base pickup state
public ItemSlotState slotState; // Current slot validation state
public string slottedItemSaveId; // Save ID of slotted item (if any)
public string slottedItemDataAssetPath; // Asset path to PickupItemData
}
// TODO: Remove this ridiculous inheritance from Pickup if possible
/// <summary>
/// Interaction requirement that allows slotting, swapping, or picking up items in a slot.
/// </summary>
@@ -178,7 +191,130 @@ namespace Interactions
}
}
public void SlotItem(GameObject itemToSlot, PickupItemData itemToSlotData, bool clearFollowerHeldItem = true)
// Register with ItemManager when enabled
protected override void Start()
{
base.Start(); // This calls Pickup.Start() which registers with save system
// Additionally register as ItemSlot
ItemManager.Instance?.RegisterItemSlot(this);
}
protected override void OnDestroy()
{
base.OnDestroy(); // Unregister from save system and pickup manager
// Unregister from slot manager
ItemManager.Instance?.UnregisterItemSlot(this);
}
#region Save/Load Implementation
protected override object GetSerializableState()
{
// Get base pickup state
PickupSaveData baseData = base.GetSerializableState() as PickupSaveData;
// Get slotted item save ID if there's a slotted item
string slottedSaveId = "";
string slottedAssetPath = "";
if (_currentlySlottedItemObject != null)
{
var slottedPickup = _currentlySlottedItemObject.GetComponent<Pickup>();
if (slottedPickup is SaveableInteractable saveablePickup)
{
slottedSaveId = saveablePickup.GetSaveId();
}
if (_currentlySlottedItemData != null)
{
#if UNITY_EDITOR
slottedAssetPath = UnityEditor.AssetDatabase.GetAssetPath(_currentlySlottedItemData);
#endif
}
}
return new ItemSlotSaveData
{
pickupData = baseData,
slotState = _currentState,
slottedItemSaveId = slottedSaveId,
slottedItemDataAssetPath = slottedAssetPath
};
}
protected override void ApplySerializableState(string serializedData)
{
ItemSlotSaveData data = JsonUtility.FromJson<ItemSlotSaveData>(serializedData);
if (data == null)
{
Debug.LogWarning($"[ItemSlot] Failed to deserialize save data for {gameObject.name}");
return;
}
// First restore base pickup state
if (data.pickupData != null)
{
string pickupJson = JsonUtility.ToJson(data.pickupData);
base.ApplySerializableState(pickupJson);
}
// Restore slot state
_currentState = data.slotState;
// Restore slotted item if there was one
if (!string.IsNullOrEmpty(data.slottedItemSaveId))
{
RestoreSlottedItem(data.slottedItemSaveId, data.slottedItemDataAssetPath);
}
}
/// <summary>
/// Restore a slotted item from save data.
/// This is called during load restoration and should NOT trigger events.
/// </summary>
private void RestoreSlottedItem(string slottedItemSaveId, string slottedItemDataAssetPath)
{
// Try to find the item in the scene by its save ID via ItemManager
GameObject slottedObject = ItemManager.Instance?.FindPickupBySaveId(slottedItemSaveId);
if (slottedObject == null)
{
Debug.LogWarning($"[ItemSlot] Could not find slotted item with save ID: {slottedItemSaveId}");
return;
}
// Get the item data
PickupItemData slottedData = null;
#if UNITY_EDITOR
if (!string.IsNullOrEmpty(slottedItemDataAssetPath))
{
slottedData = UnityEditor.AssetDatabase.LoadAssetAtPath<PickupItemData>(slottedItemDataAssetPath);
}
#endif
if (slottedData == null)
{
var pickup = slottedObject.GetComponent<Pickup>();
if (pickup != null)
{
slottedData = pickup.itemData;
}
}
// Silently slot the item (no events, no interaction completion)
ApplySlottedItemState(slottedObject, slottedData, triggerEvents: false);
}
/// <summary>
/// Core logic for slotting an item. Can be used both for normal slotting and silent restoration.
/// </summary>
/// <param name="itemToSlot">The item GameObject to slot (or null to clear)</param>
/// <param name="itemToSlotData">The PickupItemData for the item</param>
/// <param name="triggerEvents">Whether to fire events and complete interaction</param>
/// <param name="clearFollowerHeldItem">Whether to clear the follower's held item</param>
private void ApplySlottedItemState(GameObject itemToSlot, PickupItemData itemToSlotData, bool triggerEvents, bool clearFollowerHeldItem = true)
{
// Cache the previous item data before clearing, needed for OnItemSlotRemoved event
var previousItemData = _currentlySlottedItemData;
@@ -188,11 +324,10 @@ namespace Interactions
{
_currentlySlottedItemObject = null;
_currentlySlottedItemData = null;
// Clear state when no item is slotted
_currentState = ItemSlotState.None;
// Fire native event for slot clearing
if (wasSlotCleared)
// Fire native event for slot clearing (only if triggering events)
if (wasSlotCleared && triggerEvents)
{
OnItemSlotRemoved?.Invoke(previousItemData);
}
@@ -205,55 +340,53 @@ namespace Interactions
_currentlySlottedItemData = itemToSlotData;
}
if (clearFollowerHeldItem)
if (clearFollowerHeldItem && _followerController != null)
{
_followerController.ClearHeldItem();
}
UpdateSlottedSprite();
// Once an item is slotted, we know it is not forbidden, so we can skip that check, but now check if it was
// the correct item we're looking for
var config = _interactionSettings?.GetSlotItemConfig(itemData);
var allowed = config?.allowedItems ?? new List<PickupItemData>();
if (itemToSlotData != null && PickupItemData.ListContainsEquivalent(allowed, itemToSlotData))
// Only validate and trigger events if requested
if (triggerEvents)
{
if (itemToSlot != null)
// Once an item is slotted, we know it is not forbidden, so we can skip that check, but now check if it was
// the correct item we're looking for
var config = _interactionSettings?.GetSlotItemConfig(itemData);
var allowed = config?.allowedItems ?? new List<PickupItemData>();
if (itemToSlotData != null && PickupItemData.ListContainsEquivalent(allowed, itemToSlotData))
{
DebugUIMessage.Show("You correctly slotted " + itemToSlotData.itemName + " into: " + itemData.itemName, Color.green);
onCorrectItemSlotted?.Invoke();
OnCorrectItemSlotted?.Invoke(itemData, _currentlySlottedItemData);
_currentState = ItemSlotState.Correct;
if (itemToSlot != null)
{
DebugUIMessage.Show("You correctly slotted " + itemToSlotData.itemName + " into: " + itemData.itemName, Color.green);
onCorrectItemSlotted?.Invoke();
OnCorrectItemSlotted?.Invoke(itemData, _currentlySlottedItemData);
_currentState = ItemSlotState.Correct;
}
CompleteInteraction(true);
}
CompleteInteraction(true);
}
else
{
if (itemToSlot != null)
else
{
DebugUIMessage.Show("I'm not sure this works.", Color.yellow);
onIncorrectItemSlotted?.Invoke();
OnIncorrectItemSlotted?.Invoke(itemData, _currentlySlottedItemData);
_currentState = ItemSlotState.Incorrect;
if (itemToSlot != null)
{
DebugUIMessage.Show("I'm not sure this works.", Color.yellow);
onIncorrectItemSlotted?.Invoke();
OnIncorrectItemSlotted?.Invoke(itemData, _currentlySlottedItemData);
_currentState = ItemSlotState.Incorrect;
}
CompleteInteraction(false);
}
CompleteInteraction(false);
}
}
// Register with ItemManager when enabled
void Start()
/// <summary>
/// Public API for slotting items during gameplay.
/// </summary>
public void SlotItem(GameObject itemToSlot, PickupItemData itemToSlotData, bool clearFollowerHeldItem = true)
{
// Note: Base Pickup class also calls RegisterPickup in its Start
// This additionally registers as ItemSlot
ItemManager.Instance?.RegisterPickup(this);
ItemManager.Instance?.RegisterItemSlot(this);
ApplySlottedItemState(itemToSlot, itemToSlotData, triggerEvents: true, clearFollowerHeldItem);
}
void OnDestroy()
{
// Unregister from both pickup and slot managers
ItemManager.Instance?.UnregisterPickup(this);
ItemManager.Instance?.UnregisterItemSlot(this);
}
#endregion
}
}

View File

@@ -1,17 +1,30 @@
using Input;
using UnityEngine;
using System; // added for Action<T>
using System;
using System.Linq; // added for Action<T>
using Core; // register with ItemManager
namespace Interactions
{
public class Pickup : InteractableBase
/// <summary>
/// Saveable data for Pickup state
/// </summary>
[System.Serializable]
public class PickupSaveData
{
public bool isPickedUp;
public Vector3 worldPosition;
public Quaternion worldRotation;
public bool isActive;
}
public class Pickup : SaveableInteractable
{
public PickupItemData itemData;
public SpriteRenderer iconRenderer;
// Track if the item has been picked up
public bool isPickedUp { get; private set; }
public bool IsPickedUp { get; internal set; }
// Event: invoked when the item was picked up successfully
public event Action<PickupItemData> OnItemPickedUp;
@@ -22,8 +35,10 @@ namespace Interactions
/// <summary>
/// Unity Awake callback. Sets up icon and applies item data.
/// </summary>
protected virtual void Awake()
protected override void Awake()
{
base.Awake(); // Register with save system
if (iconRenderer == null)
iconRenderer = GetComponent<SpriteRenderer>();
@@ -33,16 +48,24 @@ namespace Interactions
/// <summary>
/// Register with ItemManager on Start
/// </summary>
void Start()
protected override void Start()
{
ItemManager.Instance?.RegisterPickup(this);
base.Start(); // Register with save system
// Don't register with ItemManager if already picked up (restored from save)
if (!IsPickedUp)
{
ItemManager.Instance?.RegisterPickup(this);
}
}
/// <summary>
/// Unity OnDestroy callback. Unregisters from ItemManager.
/// </summary>
void OnDestroy()
protected override void OnDestroy()
{
base.OnDestroy(); // Unregister from save system
// Unregister from ItemManager
ItemManager.Instance?.UnregisterPickup(this);
}
@@ -130,9 +153,69 @@ namespace Interactions
// Update pickup state and invoke event when the item was picked up successfully
if (wasPickedUp)
{
isPickedUp = true;
IsPickedUp = true;
OnItemPickedUp?.Invoke(itemData);
}
}
#region Save/Load Implementation
protected override object GetSerializableState()
{
return new PickupSaveData
{
isPickedUp = this.IsPickedUp,
worldPosition = transform.position,
worldRotation = transform.rotation,
isActive = gameObject.activeSelf
};
}
protected override void ApplySerializableState(string serializedData)
{
PickupSaveData data = JsonUtility.FromJson<PickupSaveData>(serializedData);
if (data == null)
{
Debug.LogWarning($"[Pickup] Failed to deserialize save data for {gameObject.name}");
return;
}
// Restore picked up state
IsPickedUp = data.isPickedUp;
if (IsPickedUp)
{
// Hide the pickup if it was already picked up
gameObject.SetActive(false);
}
else
{
// Restore position for items that haven't been picked up (they may have moved)
transform.position = data.worldPosition;
transform.rotation = data.worldRotation;
gameObject.SetActive(data.isActive);
}
// Note: We do NOT fire OnItemPickedUp event during restoration
// This prevents duplicate logic execution
}
/// <summary>
/// Resets the pickup state when the item is dropped back into the world.
/// Called by FollowerController when swapping items.
/// </summary>
public void ResetPickupState()
{
IsPickedUp = false;
gameObject.SetActive(true);
// Re-register with ItemManager if not already registered
if (ItemManager.Instance != null && !ItemManager.Instance.GetAllPickups().Contains(this))
{
ItemManager.Instance.RegisterPickup(this);
}
}
#endregion
}
}

View File

@@ -0,0 +1,261 @@
using Core.SaveLoad;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Interactions
{
/// <summary>
/// Base class for interactables that participate in the save/load system.
/// Provides common save ID generation and serialization infrastructure.
/// </summary>
public abstract class SaveableInteractable : InteractableBase, ISaveParticipant
{
[Header("Save System")]
[SerializeField]
[Tooltip("Optional custom save ID. If empty, will auto-generate from hierarchy path.")]
private string customSaveId = "";
/// <summary>
/// Flag to indicate we're currently restoring from save data.
/// Child classes can check this to skip initialization logic during load.
/// </summary>
protected bool IsRestoringFromSave { get; private set; }
private bool hasRegistered;
private bool hasRestoredState;
/// <summary>
/// Returns true if this participant has already had its state restored.
/// </summary>
public bool HasBeenRestored => hasRestoredState;
protected virtual void Awake()
{
// Register early in Awake so even disabled objects are tracked
RegisterWithSaveSystem();
}
protected virtual void Start()
{
// If we didn't register in Awake (shouldn't happen), register now
if (!hasRegistered)
{
RegisterWithSaveSystem();
}
}
protected virtual void OnDestroy()
{
UnregisterFromSaveSystem();
}
private void RegisterWithSaveSystem()
{
if (hasRegistered) return;
if (SaveLoadManager.Instance != null)
{
SaveLoadManager.Instance.RegisterParticipant(this);
hasRegistered = true;
// Check if save data was already loaded before we registered
// If so, we need to subscribe to the next load event
if (!SaveLoadManager.Instance.IsSaveDataLoaded && !hasRestoredState)
{
SaveLoadManager.Instance.OnLoadCompleted += OnSaveDataLoadedHandler;
}
}
else
{
Debug.LogWarning($"[SaveableInteractable] SaveLoadManager not found for {gameObject.name}");
}
}
private void UnregisterFromSaveSystem()
{
if (!hasRegistered) return;
if (SaveLoadManager.Instance != null)
{
SaveLoadManager.Instance.UnregisterParticipant(GetSaveId());
SaveLoadManager.Instance.OnLoadCompleted -= OnSaveDataLoadedHandler;
hasRegistered = false;
}
}
/// <summary>
/// Event handler for when save data finishes loading.
/// Called if the object registered before save data was loaded.
/// </summary>
private void OnSaveDataLoadedHandler(string slot)
{
// The SaveLoadManager will automatically call RestoreState on us
// We just need to unsubscribe from the event
if (SaveLoadManager.Instance != null)
{
SaveLoadManager.Instance.OnLoadCompleted -= OnSaveDataLoadedHandler;
}
}
#region ISaveParticipant Implementation
public string GetSaveId()
{
string sceneName = GetSceneName();
if (!string.IsNullOrEmpty(customSaveId))
{
return $"{sceneName}/{customSaveId}";
}
// Auto-generate from hierarchy path
string hierarchyPath = GetHierarchyPath();
return $"{sceneName}/{hierarchyPath}";
}
public string SerializeState()
{
object stateData = GetSerializableState();
if (stateData == null)
{
return "{}";
}
return JsonUtility.ToJson(stateData);
}
public void RestoreState(string serializedData)
{
if (string.IsNullOrEmpty(serializedData))
{
Debug.LogWarning($"[SaveableInteractable] Empty save data for {GetSaveId()}");
return;
}
// CRITICAL: Only restore state if we're actually in a restoration context
// This prevents state machines from teleporting objects when they enable them mid-gameplay
if (SaveLoadManager.Instance != null && !SaveLoadManager.Instance.IsRestoringState)
{
// If we're not in an active restoration cycle, this is probably a late registration
// (object was disabled during initial load and just got enabled)
// Skip restoration to avoid mid-gameplay teleportation
Debug.Log($"[SaveableInteractable] Skipping late restoration for {GetSaveId()} - object enabled after initial load");
hasRestoredState = true; // Mark as restored to prevent future attempts
return;
}
IsRestoringFromSave = true;
hasRestoredState = true;
try
{
ApplySerializableState(serializedData);
}
catch (System.Exception e)
{
Debug.LogError($"[SaveableInteractable] Failed to restore state for {GetSaveId()}: {e.Message}");
}
finally
{
IsRestoringFromSave = false;
}
}
#endregion
#region Virtual Methods for Child Classes
/// <summary>
/// Child classes override this to return their serializable state data.
/// Return an object that can be serialized with JsonUtility.
/// </summary>
protected abstract object GetSerializableState();
/// <summary>
/// Child classes override this to apply restored state data.
/// Should NOT trigger events or re-initialize logic that already happened.
/// </summary>
/// <param name="serializedData">JSON string containing the saved state</param>
protected abstract void ApplySerializableState(string serializedData);
#endregion
#region Helper Methods
private string GetSceneName()
{
Scene scene = gameObject.scene;
if (!scene.IsValid())
{
Debug.LogWarning($"[SaveableInteractable] GameObject {gameObject.name} has invalid scene");
return "UnknownScene";
}
return scene.name;
}
private string GetHierarchyPath()
{
// Build path from scene root to this object
// Format: ParentName/ChildName/ObjectName_SiblingIndex
string path = gameObject.name;
Transform current = transform.parent;
while (current != null)
{
path = $"{current.name}/{path}";
current = current.parent;
}
// Add sibling index for uniqueness among same-named objects
int siblingIndex = transform.GetSiblingIndex();
if (siblingIndex > 0)
{
path = $"{path}_{siblingIndex}";
}
return path;
}
#endregion
#region Editor Helpers
#if UNITY_EDITOR
[ContextMenu("Log Save ID")]
private void LogSaveId()
{
Debug.Log($"Save ID: {GetSaveId()}");
}
[ContextMenu("Test Serialize/Deserialize")]
private void TestSerializeDeserialize()
{
string serialized = SerializeState();
Debug.Log($"Serialized state: {serialized}");
RestoreState(serialized);
Debug.Log("Deserialization test complete");
}
#endif
#endregion
}
#region Common Save Data Structures
/// <summary>
/// Base save data for all interactables.
/// Can be extended by child classes.
/// </summary>
[System.Serializable]
public class InteractableBaseSaveData
{
public bool isActive;
public Vector3 worldPosition;
public Quaternion worldRotation;
}
#endregion
}

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a0d7c8f7344746ce9dc863985cc3f543
timeCreated: 1762079555