I'm using GameSparks with unity and I'm trying to pull certain data from the database.
I set up an event called "getItem" with an attribute "type" set to "used in script".
I set up a cloud code event to to access that event via the using the "type" attribute, which will actually access the description field in the data.
var description = Spark.getData().type; // get the type we passed in
if(description !== ""){
// if the type wasnt an empty string, then we can use the type in our query
Spark.setScriptData('items', Spark.metaCollection('items').find({"description": description}));
}
In the Test Harness, I authenticate and then go the Log Event with this JSON
{
"@class": ".LogEventRequest",
"eventKey": "getItem",
"type": "Sharp"
}
In the inspector I see Statement Count: 2 with the request and response of
{
"@class": ".LogEventResponse",
"scriptData": {
"items": [
{
"_id": {
"$oid": "59160a27feeace0001d90f7f"
},
"shortCode": "sword",
"name": "Stone Sword",
"description": "Sharp",
}
]
}
}
In my Unity code I have everything set up, I authenticate, and on button click it calls this:
new GameSparks.Api.Requests.LogEventRequest()
.SetEventKey("getItem")
.SetEventAttribute("type", "Sharp")
.Send((response) => {
if (!response.HasErrors) {
GSData data = response.ScriptData.GetGSData("items");
print("Item ID: " + data.GetString("name"));
} else {
Debug.Log("Error Saving Player Data...");
}
});
Thats when I get a stream of "object reference not set to an instance of an object"
If I remove the print statement it doesn't throw errors. It seems to just not be finding any descriptions of sharp even though the test harness does.
I've tried many variations of the code but can't get it to work.
As you correctly spotted, the error was coming from a mismatch between the data in your response and the getter you were using to retrieve it.
Since your 'items' field contains an array you'd need to use
List data = response.ScriptData.GetGSDataList("items");
and iterate through the list.
To return a single object rather than an array you could change your cloud code query to:
Spark.metaCollection('items').findOne({"description": description})
Note that if multiple documents satisfy the query provided, mongo will return the first document it finds.
If you have any further questions or run into any problems while using GameSparks, you can contact our support team via - https://support.gamesparks.net/support/home