Script structure
In a Cloud Code API script, the main function that acts as the entry point of the runtime takes the form of a CommonJS wrapper.
The following code snippet shows the simplest possible script:
JavaScript
module.exports = async ({ params, context, logger }) => {
// this script does nothing
};
While this script doesn’t actually do anything, it shows the context object and asynchronous nature of the script function.
A script is invalid unless it exports a CommonJS function.
Context object
The context object contains these useful objects:
Params
: This is an array of name-value pairs of the input parameters with which a script is called.Context
: This object provides additional context that is useful within a script:projectId
: The project ID to which the caller was authenticated.playerId
: The authenticated player ID.accessToken
: A JWT that can be used to call other Unity game services SDKs as the authenticated player.environmentName
: The name of the currently used Unity environment.environmentId
: The ID of the currently used Unity environment.
Logger
: An object that allows the script to log info, warnings, and errors.
JavaScript
module.exports = async ({logger}) => {
logger.info('This message confirms that the logging client is functional!');
logger.warning('This is a serious warning that the cheese is about to run out.');
logger.error('Out of cheese :(');
}
Async/await
The main script function can be an asynchronous function. This means that a function can await promises, which enables the use of other Unity game service SDKs within the script. See the Mozilla documentation describing promises.
A trivial example looks like the following:
JavaScript
// Player inventory
const { InventoryApi } = require("@unity-services/economy-2.3");
module.exports = async ({params, context, logger}) => {
const { projectId, playerId } = context;
const inventory = new InventoryApi(context);
const result = await inventory.getPlayerInventory({projectId, playerId});
return result.data;
}
Cloud Code client-side calls are always asynchronous, with both regular (synchronous) and asynchronous scripts. This means that the editor integration does not change depending on script type.