Untitled
unknown
plain_text
9 months ago
3.8 kB
12
Indexable
public class ResourceInteraction : MonoBehaviour, IInteractable, IDataPersistence
{
[SerializeField] private ResourceType resourceType;
public string resourceID { get; private set; }
public event Action OnResourceCollected;
private bool isCollected = false;
private void Awake()
{
resourceID = string.Empty;
}
void Start()
{
if (SaveManager.Instance != null)
{
var saveData = SaveManager.Instance.GetSaveData();
if (saveData != null)
{
LoadData(saveData);
}
}
else
{
Debug.LogError("SaveManager Instance is null! Ensure SaveManager is initialized before calling this.");
}
// Only generate a new resource ID if one was NOT assigned from save data
if (string.IsNullOrEmpty(resourceID))
{
Debug.Log("Generating new resource ID");
resourceID = Guid.NewGuid().ToString();
}
}
public void LoadData(GameSaveData data)
{
// Ensure the resource ID is restored from saved data
if (data.resourceIDs.TryGetValue(resourceType, out var resourceSet))
{
foreach (var savedID in resourceSet)
{
if (string.IsNullOrEmpty(resourceID)) // Ensure only unassigned IDs get restored
{
resourceID = savedID;
Debug.Log("Restored resource ID: " + resourceID);
break;
}
}
}
if (data.collectedResources.TryGetValue(resourceType, out var resourceDict))
{
Debug.Log($"The resource type {resourceType} exists and has loaded");
// Check if the specific resource instance (resourceID) exists
if (resourceDict.TryGetValue(resourceID, out bool collected))
{
isCollected = collected; // Update the isCollected status
Debug.Log("Loaded");
// If it was already collected, remove it from the scene
if (isCollected)
{
Debug.Log("Already used");
Destroy(gameObject); // Destroy the resource if it was already collected
}
}
}
}
public void SaveData(ref GameSaveData data)
{
if (string.IsNullOrEmpty(resourceID))
{
Debug.LogError("Resource ID is null or empty, cannot save.");
return;
}
// Ensure dictionary structure exists
if (!data.collectedResources.ContainsKey(resourceType))
{
data.collectedResources[resourceType] = new Dictionary<string, bool>();
}
data.collectedResources[resourceType][resourceID] = isCollected;
// Ensure resourceIDs set exists
if (!data.resourceIDs.ContainsKey(resourceType))
{
data.resourceIDs[resourceType] = new HashSet<string>();
}
if (!data.resourceIDs[resourceType].Contains(resourceID))
{
data.resourceIDs[resourceType].Add(resourceID);
}
Debug.Log($"Saved resource {resourceID} with collected state: {isCollected}");
}
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
Interact();
isCollected = true;
SaveManager.Instance.SaveGame();
Destroy(gameObject);
}
}
public void Interact()
{
ResourceManager.Instance.AddResource(resourceType, 1);
}
}Editor is loading...
Leave a Comment