On GameSparks, there are scripts that have player context and scripts that don't have player context. In this article, we'll run through both types and talk a little about why player context is important.

Scripts with and Scripts without Player Context

Scripts with Player Context

Scripts that have player context are:

  • LogEventRequests and LogChallengeEventRequests Cloud Code Scripts (when the event is sent from the client).
  • User Message Cloud Code Scripts
  • A Callback URL script can have player context if a playerId is part of the url. See our guide on Callbacks here for more details.
  • Scheduled Module Cloud Code Scripts
  • Player Connected System Cloud Code Script
  • Player Disconnected System Cloud Code Script

Scripts without Player Context

Scripts that don't have player context include:

  • System Cloud Code Scripts not specified above.
    • Every day
    • Every Minute
    • Every Hour
    • Game Published
  • Global Message Cloud Code Scripts (see here for the difference between Global and User messages)

Typical Use Cases using Player Context

Player context in a script is useful because it allows the script to make use of the SparkPlayer API. Access to this API serves some very typical use cases:

  • Performing Additional Checks in Logic
  • Using the Player Object's scriptData and privateData
  • Accessing Stored Player Data

Additional Checks in Logic

With player context, you can add some additional checks in your logic. For example:

//check if the user has 3 or more of the vgood type gold
var vgCheck = Spark.getPlayer().hasVGood("gold")

if(vgCheck >= 3){
    //do this

//check if a user has this achievement
var achCheck = Spark.getPlayer().hasAchievement("achievement")

if (achCheck == true){
    //do this

Using the Player Object's scriptData and privateData

Having player context in a script will also let you make use of the player object's scriptData and privateData fields:

//set some scriptdata to the player
Spark.getPlayer().setScriptData("myScriptData", "value")

//get the scriptData value

//set some privateData to the player
Spark.getPlayer().setPrivateData("myPrivateData", "value")

//get the privateData value

Accessing Stored Player Data

When storing player data in a data type, it's a good idea to use playerId as the id for the document that you are storing. Doing this will allow you to easily access the document in Cloud Code and you'll know the id is unique to that player:

//Get Game Service Data API

var API = Spark.getGameDataService();

//create a document using the player id as the id
var entry = API.createItem("player", Spark.getPlayer().getPlayerId() );

//create some test data to add
var data = {"test":"data"}

//persist the data

If you need to store multiple documents for a player, then you could use the playerId field as one of your indexed fields and query by that indexed field to return the documents. See here for details on how to set up your game data types.