Skip to content

Instantly share code, notes, and snippets.

@iaincollins
Last active February 14, 2024 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iaincollins/3ca54bc750c6d0bc84c2a559ba0d400e to your computer and use it in GitHub Desktop.
Save iaincollins/3ca54bc750c6d0bc84c2a559ba0d400e to your computer and use it in GitHub Desktop.
Using Unity Cloud Save for Game Logic

Here is an example of how it's possible to do something like player matching with Unity Cloud Save SDK 3.1

  1. Write to the data you want to use for matching (e.g. region, language, level, etc) to Player Data in the Public Access Class (Public Data is readable by other players).
using SaveOptions = Unity.Services.CloudSave.Models.Data.Player.SaveOptions;

var data = new Dictionary<string, object> { { "location", "Paris" } };
await CloudSaveService.Instance.Data.Player.SaveAsync(data, new SaveOptions(new PublicWriteAccessClassOptions()));

Note: Before saving data, first define an Index for them (e.g. in the Unity Cloud Dashboard or using the Unity CLI) so that you can query these keys in the next step. Indexes should be defined before writing to them.

  1. Find other players using a query
var query = new Query(
  new List<FieldFilter> {
    new FieldFilter("location", "Paris", FieldFilter.OpOptions.EQ, true)
  },
  { "location", "name", "avatar" } // List of Public data keys to return along with results
);
var results = await CloudSaveService.Instance.Data.Player.QueryAsync(query);

Debug.Log($"Number of players returned {results.Count}");
results.ForEach(r => {
  Debug.Log($"Player ID: {r.Id}");
  r.Data.ForEach(d => Log($"Key: {d.Key}, Value: {d.Value.GetAsString()}"));
});
  1. At this point you can either add client side game logic - and potentially record the outcome on a leaderboard - or, if's a competitive game and you want to prevent cheating, add server authoritative game logic using Cloud Code or a game server and use Cloud Save Game Data to persist the game state.

You could of course use full server authortaitive logic for the game client matching, and use data in the Protected Access Class (which game client cannot write to directly), but there are tradeoffs and the appropriate level of complexity is going to vary depending on the use case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment