How to use AWS SDK in Unity for WebGL builds?
So you want to use AWS services in your Unity game/app and also figured out how to setup & use the AWS SDK for .NET but then realise it doesn’t work for WebGL builds, right?
The TL;DR solution is to use AWS SDK for JavaScript in Unity that works with the WebGL builds.
Keep reading if you are curious on how to setup and call JavaScript functions from C# scripts with an example of using AWS Firehose service in Unity for WebGL to send your data.
The whole process can be divided into 2 parts:
- We create a
.jslibfile in our Unity project which has our JavaScript functions and useSystem.Runtime.InteropServicesto call those functions from C# script.
Read more about it in Unity’s documentation. - We either load the AWS SDK for JavaScript in runtime from a server or include it in the build itself.
Setting up your script files and the code to send data using AWS Firehose
1.It is essential that the .jslib file with our JavaScript functions must be placed inside Assets > Plugins folder of our project. I personally create another subfolder, WebGL, inside Plugins folder. Let’s call this file AWSFirehose.jslib
2. Open the file in your code editor and type in the below lines.
Even if you ignore the first line where we declare the variable, rest of the template has to be exactly same.
var firehoseClient = null; //Globally accessible AWS client
mergeInto(LibraryManager.library, {
//All of our code goes inside this curly braces.
});Note: Comments are not allowed so don’t actually add them in your file else you’ll get errors.
3. Before interacting with AWS services, it’s crucial to perform the AWS client configuration. Instead of hardcoding sensitive credentials like secret keys and access keys, it’s recommended to utilise AWS Cognito or other secure identity management methods for a more robust approach to AWS configuration.
But for this example, I’ll be hardcoding them. Again, not a recommended way of doing it.
var firehoseClient = null; //Globally accessible AWS client
mergeInto(LibraryManager.library, {
AWSFirehose_Init: function (accessKey, secretKey, region) {
if(typeof AWS === 'undefined')
{
console.log("AWS SDK not available");
return;
}
if(typeof AWS.Firehose === 'undefined')
{
console.log("Firehose service not available");
return;
}
var ak = UTF8ToString(accessKey);
var sk = UTF8ToString(secretKey);
var rg = UTF8ToString(region);
AWS.config.update({
accessKeyId: ak,
secretAccessKey: sk,
region: rg
});
firehoseClient = new AWS.Firehose();
}
});4. Next, we write the function that actually sends our data.
var firehoseClient = null; //Globally accessible AWS client
mergeInto(LibraryManager.library, {
//Initialising Client
AWSFirehose_Init: function (accessKey, secretKey, region) {
if(typeof AWS === 'undefined')
{
console.log("AWS SDK not available");
return;
}
if(typeof AWS.Firehose === 'undefined')
{
console.log("Firehose service not available");
return;
}
var ak = UTF8ToString(accessKey);
var sk = UTF8ToString(secretKey);
var rg = UTF8ToString(region);
AWS.config.update({
accessKeyId: ak,
secretAccessKey: sk,
region: rg
});
firehoseClient = new AWS.Firehose();
}, //Don't forget this comma here before defining our next function
//Sending Data
AWSFirehose_PutRecord: function (dataPointer, streamName) {
if (typeof firehoseClient === 'undefined') {
console.error("AWS not initialized.");
return;
}
//Data json to be sent
var dataString = UTF8ToString(dataPointer);
//Stream on which the data has to be sent
var stream = UTF8ToString(streamName);
function attemptPutRecord() {
var params = {
DeliveryStreamName: stream,
Record: {
Data: dataString
}
};
firehoseClient.putRecord(params, function (err, data) {
if (err) {
console.log("Error sending data...", err);
}
});
}
attemptPutRecord();
}
});5. We are done with our .jslib file. Now create a new C# script, AWSFirehose.cs, from where we’ll call our JavaScript functions.
In order to do so, we have to use System.Runtime.InteropServices as well as hard code the credentials.
using UnityEngine;
using System.Runtime.InteropServices;
public class AWSFirehose : MonoBehaviour
{
private readonly string accessKey = "dummyAccessKey";
private readonly string secretKey = "dummySecretKey";
private readonly Amazon.RegionEndpoint region = Amazon.RegionEndpoint.EUNorth1;
}Note: As mentioned at the beginning, assuming you have already setup AWS SDK for .NET in Unity, you’ll have access to
Amazon.RegionEndpointclass else make theregionvariable of type string, because anyway further in thisAWSFirehose.csscript’s Start method, we’ll be using one of it’s property calledSystemNamewhich is of type string.
6. Next, we declare the methods/functions we defined in AWSFirehose.jslib[DllImport(“__Internal”)] attribute indicates that we want to call a function from a native library or external code.
Make sure the method name is same as the one in .jslib and the order and type of parameters is correct as well.
using UnityEngine;
using System.Runtime.InteropServices;
public class AWSFirehose : MonoBehaviour
{
private readonly string accessKey = "dummyAccessKey";
private readonly string secretKey = "dummySecretKey";
private readonly Amazon.RegionEndpoint region = Amazon.RegionEndpoint.EUNorth1;
[DllImport("__Internal")]
private static extern void AWSFirehose_Init(string accessKey, string secretKey, string region);
[DllImport("__Internal")]
private static extern void AWSFirehose_PutRecord(string data, string streamName);
}7. Finally in Start method, we initialise the AWS client and another method to send the data. With that we finish the scripting part.
using UnityEngine;
using System.Runtime.InteropServices;
public class AWSFirehose : MonoBehaviour
{
private readonly string accessKey = "dummyAccessKey";
private readonly string secretKey = "dummySecretKey";
private readonly Amazon.RegionEndpoint region = Amazon.RegionEndpoint.EUNorth1;
[DllImport("__Internal")]
private static extern void AWSFirehose_Init(string accessKey, string secretKey, string region);
[DllImport("__Internal")]
private static extern void AWSFirehose_PutRecord(string data, string streamName);
private void Start()
{
AWSFirehose_Init(accessKey, secretKey, region.SystemName);
}
public void SendDataToFirehose(string data, string stream)
{
AWSFirehose_PutRecord(data, stream);
}
}Loading the AWS SDK for JavaScript in the build.
1.Go on and build the WebGL build in Unity from the Build Settings as one usually builds for each platform.
2. Once the build has finished, you get an index.html and a Build folder. Open up index.html in your code editor.
3. This step is utmost important. We need to add <script> tag to include external JavaScript files in a web page. This is how we will be loading our AWS SDK for JavaScript. Add this tag preferably inside the <head> tag.
4. Now there are 2 ways you can load the SDK.
- Loading the hosted SDK package directly from Amazon Web Services or from your own server.
- Download the package manually and including the SDK package in the previously mentioned
Buildfolder before hosting the game.
If loading the package from server:
In case you want to load the SDK from AWS’s server, add the line:
<script src="https://sdk.amazonaws.com/js/aws-sdk-SDK_VERSION_NUMBER.min.js"></script>I recently used v2.1475.0 so the code would be:
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1475.0.min.js"></script>Just replace the source link in case you want it to load from your server. Why would you do so though? Keep reading to know one of the reasons.
Documentation sauce for loading the SDK from a server, switch to Browser tab from Node tab: AWS Doc
If including the package in Build folder:
- Download the minified version from AWS’s GitHub repo: Repository
- Place it inside the
Buildfolder.
Line of code to add in the index.html in this case would be the local path of the package.
<script src="Build/DOWNLOADED_PACKAGE_NAME.js"></script>Your index.html should probably look like this depending on how you choose to load the SDK.
Create your own build of the AWS SDK for JavaScript.
You can create a custom build of the AWS SDK by only including the services you’re using in the project.
The easiest way is to use AWS’s SDK builder web application:
https://sdk.amazonaws.com/builder/js
- Select the SDK version from Core version dropdown.
- Select the services you want to include.
- Select either Minified or Development. Development generates readable code.
- Then click on Build button to download the package.
There are other ways to build your own SDK as well, you can find it in the documentation.
Now you can either host this downloaded package on your own server or put it in the Build folder as mentioned previously.
You are ready to deploy your WebGL build and test out the services.
We have reached the end of the guide. That was the complete process of making the AWS SDK for JavaScript work in WebGL builds.
If in doubt, just ask! Cheers o/
