Skip to content

Commit

Permalink
namespace offline saves by player id, fix first save being -1
Browse files Browse the repository at this point in the history
  • Loading branch information
tudddorrr committed Sep 16, 2024
1 parent 7c133b8 commit 395e2cc
Showing 1 changed file with 26 additions and 10 deletions.
36 changes: 26 additions & 10 deletions Packages/com.trytalo.talo/Runtime/APIs/SavesAPI.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public class SavesAPI : BaseAPI
public event Action<GameSave> OnSaveChosen;
public event Action OnSaveLoadingCompleted;

private readonly string _offlineSavesPath = Application.persistentDataPath + "/ts.bin";
private IFileHandler<OfflineSavesContent> _fileHandler;

public GameSave[] All
Expand Down Expand Up @@ -148,18 +147,35 @@ public void Register(Loadable loadable)
_registeredLoadables.Add(new LoadableData(loadable));
}

internal string GetOfflineSavesPath()
{
return Application.persistentDataPath + $"/ts.{Talo.CurrentPlayer.id}.bin";
}

internal OfflineSavesContent GetOfflineSavesContent()
{
return _fileHandler.ReadContent(_offlineSavesPath);
return _fileHandler.ReadContent(GetOfflineSavesPath());
}

internal void WriteOfflineSavesContent(OfflineSavesContent newContent)
{
_fileHandler.WriteContent(_offlineSavesPath, newContent);
_fileHandler.WriteContent(GetOfflineSavesPath(), newContent);
}

private GameSave CreateOfflineCopy(GameSave originalSave)
{
return new GameSave
{
id = originalSave.id,
name = originalSave.name,
content = originalSave.content,
updatedAt = originalSave.updatedAt
};
}

private void UpdateOfflineSaves(GameSave incomingSave)
{
var offlineIncomingSave = CreateOfflineCopy(incomingSave);
var offlineContent = GetOfflineSavesContent();
var updated = false;

Expand All @@ -168,30 +184,30 @@ private void UpdateOfflineSaves(GameSave incomingSave)
// updating
offlineContent.saves = offlineContent.saves.Select((existingSave) =>
{
if (existingSave.id == incomingSave.id)
if (existingSave.id == offlineIncomingSave.id)
{
updated = true;
return incomingSave;
return offlineIncomingSave;
}
return existingSave;
}).ToArray();

// appending
if (!updated)
{
if (incomingSave.id == 0)
if (offlineIncomingSave.id == 0)
{
incomingSave.id = -offlineContent.saves.Length - 1;
offlineIncomingSave.id = -offlineContent.saves.Length - 1;
}

offlineContent.saves = offlineContent.saves.Concat(new GameSave[] { incomingSave }).ToArray();
offlineContent.saves = offlineContent.saves.Concat(new GameSave[] { offlineIncomingSave }).ToArray();
}
}
else
{
// first entry into the saves file
incomingSave.id = -1;
offlineContent = new OfflineSavesContent(new GameSave[] { incomingSave });
offlineIncomingSave.id = -1;
offlineContent = new OfflineSavesContent(new GameSave[] { offlineIncomingSave });
}

WriteOfflineSavesContent(offlineContent);
Expand Down

0 comments on commit 395e2cc

Please sign in to comment.