How To Host Unity WebGL Builds On LMS With xAPI Tracking

In this guide, we’ll walk you through the process of hosting a Unity WebGL game on an Learning Management System (LMS) with xAPI tracking. LMS platforms like SCORM Cloud are popular for delivering and tracking online learning content. By integrating xAPI (Experience API)—a modern learning technology standard—into your Unity project, you can track detailed learner interactions and send this data to your chosen LMS. In this guide, we’ll use SCORM Cloud as an example, but the steps are applicable to any xAPI-compliant LMS platform.

Whether you’re creating a serious game, a training simulation, or an educational experience, this guide will help you set up your project to communicate with any xAPI-enabled LMS, ensuring that you can track and report learner progress effectively.

We’ll cover everything from setting up your LMS account (using SCORM Cloud as an example), preparing your Unity WebGL project for xAPI tracking, creating and configuring a custom WebGL template, to uploading and testing your project on the LMS. By the end of this guide, you’ll have a fully functional WebGL build that sends xAPI statements to an Learning Record Store (LRS).

1. Setting Up Your LMS Account

Before you can start hosting your Unity WebGL build on your chosen LMS with xAPI tracking, you need to set up an account and configure an application. Here’s how you can do it (using SCORM Cloud as an example):

1.1 Create an Account

If you don’t already have an account on your LMS, you’ll need to create one. Many LMS platforms, like SCORM Cloud, offer various plans, including free options to get started with basic features.

  • Choose an LMS Platform: Select an LMS that supports xAPI tracking. Popular options include SCORM Cloud, Moodle, Learning Locker, and Docebo.
  • Create an Account: Go to your chosen LMS platform and sign up for an account.
  • Log In: Once your account is created, log in to your LMS dashboard.

1.2 Create an Application or Integration

To integrate your Unity WebGL project with an LMS, you need to create an application or set up API credentials within your LMS account. Here’s how you can do it (we’ll use SCORM Cloud as an example):

  • In the LMS dashboard, go to the Apps section (for SCORM Cloud).
    Click on “Add App” to create a new application.
  • Enter a name for your application and configure any other settings as needed.
  • Once your app is created, you’ll be provided with an App ID and a Secret Key. Keep these credentials handy, as you’ll need them to configure your Unity project.

1.3 Understanding the Credentials

  • App ID: This serves as your username when making xAPI requests.
  • Secret Key: This is your password for xAPI authentication.
  • LRS Endpoint: This is the URL where you’ll send the xAPI statements. The endpoint format for SCORM Cloud is https://cloud.scorm.com/lrs/YOUR_APP_ID/statements, but it may vary for other LMS platforms.
Understanding the Credentials

In the next section, we’ll dive into preparing your Unity WebGL project for xAPI integration.

2. Implementing xAPI in Your Unity WebGL Project

In this section, we’ll guide you through implementing xAPI tracking in your Unity WebGL project using a custom XAPIManager script. This script generates xAPI statements (structured data about learner activities) and sends them to the LRS of your chosen LMS.

2.1 Creating the XAPIManager Script

To start, create a script in Unity that will handle sending xAPI statements to the LRS.

  1. Create the XAPIManager Script:
    • In Unity, go to the Assets folder and create a new C# script named XAPIManager.
    • Open the script in your preferred code editor.

Implement the Script:

Replace the content of the XAPIManager script with the following code: (Remember to replace YOUR_LRS_ID and YOUR_LRS_SecretKey with the App ID and Secret Key provided by your LMS platform.)


using System.Collections;
using UnityEngine;
using UnityEngine.Networking;

public class XAPIManager : MonoBehaviour
{
    private string endpoint = 
"https://cloud.scorm.com/lrs/YOUR_LRS_ID/statements";
    private string username = "YOUR_LRS_ID";
    private string password = "YOUR_LRS_SecretKey";

    public void SendStatement(string actorName, string actorEmail, string verbId, 
string verbDisplay, string activityId, string activityName, 
string activityDescription)
    {
        // Use default values if name or email is not provided
        if (string.IsNullOrEmpty(actorName)) actorName = "Tester";
        if (string.IsNullOrEmpty(actorEmail)) actorEmail = "tester@test.com";

        string jsonStatement = GenerateStatement(actorName, actorEmail, verbId, 
verbDisplay, activityId, activityName, activityDescription);
        StartCoroutine(PostStatement(jsonStatement));
    }

    private IEnumerator PostStatement(string jsonStatement)
    {
        UnityWebRequest request = new UnityWebRequest(endpoint, "POST");
        byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(jsonStatement);
        request.uploadHandler = new UploadHandlerRaw(bodyRaw);
        request.downloadHandler = new DownloadHandlerBuffer();
        request.SetRequestHeader("Content-Type", "application/json");
        request.SetRequestHeader("X-Experience-API-Version", "1.0.3");

        string auth = System.Convert.ToBase64String(System.Text.Encoding.ASCII.
GetBytes(username + ":" + password));
        request.SetRequestHeader("Authorization", "Basic " + auth);

        yield return request.SendWebRequest();

        if (request.result == UnityWebRequest.Result.Success)
        {
            Debug.Log("Successfully sent xAPI statement");
        }
        else
        {
            Debug.LogError("Error sending xAPI statement: " + request.error);
            Debug.LogError("Response: " + request.downloadHandler.text);
        }
    }

    private string GenerateStatement(string actorName, string actorEmail, 
string verbId, string verbDisplay, string activityId, string activityName, 
string activityDescription)
    {
        return $@"
        {{
            ""actor"": {{
                ""name"": ""{actorName}"",
                ""mbox"": ""mailto:{actorEmail}""
            }},
            ""verb"": {{
                ""id"": ""{verbId}"",
                ""display"": {{ ""en-GB"": ""{verbDisplay}"" }}
            }},
            ""object"": {{
                ""id"": ""{activityId}"",
                ""definition"": {{
                    ""name"": {{ ""en-GB"": ""{activityName}"" }},
                    ""description"": {{ ""en-GB"": ""{activityDescription}"" }}
                }}
            }}
        }}";
    }
}


  1. Explanation:
    • Endpoint, Username, Password: These fields are required to authenticate and send data to the LRS. Replace “YOUR_LRS_ID” and “YOUR_LRS_SecretKey” with your actual LMS credentials.
    • SendStatement: This method generates an xAPI statement and sends it to the LRS. It takes parameters like actorName, actorEmail, verbId, verbDisplay, activityId, activityName, and activityDescription.
    • PostStatement: This coroutine handles the HTTP POST request to send the statement to the LRS.
    • GenerateStatement: This method creates the JSON structure for the xAPI statement.

2.2 Using the XAPIManager in Your Unity Project

To send an xAPI statement, you’ll need to call the SendStatement method from within your Unity project. Here’s a simple example:

  1. Attach the XAPIManager to a GameObject:
    • In Unity, create an empty GameObject in your scene (e.g., named XAPIManager).
    • Attach the XAPIManager script to this GameObject.

Call the SendStatement Method:

Here’s a basic example of how to call the SendStatement method when a player completes the game:


public class GameCompletionHandler : MonoBehaviour
{
    public XAPIManager xapiManager;

    void Start()
    {
        // Find the XAPIManager in the scene
        xapiManager = FindObjectOfType();
    }

    public void OnGameComplete()
    {
        // Send a completion statement when the game is completed
        xapiManager.SendStatement(
            actorName: "Player Name",         // Replace with actual player name
            actorEmail: "player@example.com", // Replace with actual player email
            verbId: "http://adlnet.gov/expapi/verbs/completed",
            verbDisplay: "completed",
            activityId: "http://yourdomain.com/activities/your-activity-id",
            activityName: "Your Game Name",
            activityDescription: "Completed the game."
        );
    }
}

  1. Explanation:
    • OnGameComplete: This method is triggered when the player completes the game. It calls the SendStatement method of the XAPIManager to send a completion statement to the LRS.
    • In a real project, you should capture the player’s name and email dynamically, perhaps through a login screen or user input fields.
  1. Note: In a real project, you would replace “Player Name” and “player@example.com” with actual dynamic values, such as those entered by the user.

2.3 Testing the XAPIManager in Unity

To test the functionality:

  1. In Play Mode:
    • Run your game in the Unity Editor and simulate game completion. The xAPI statement will be generated, and you’ll see the result in the Unity console.
  1. In WebGL Build:
    • Once you build and deploy the game, the xAPI statements will be sent to the LRS as expected.

By following these steps, you’ve now integrated xAPI tracking into your Unity project. In the next section, we’ll cover how to create a custom WebGL template and upload your project to an LMS.

3. Preparing Your Unity WebGL Project for xAPI Integration

In this section, we’ll walk through creating a custom WebGL template for your Unity project. This custom template is essential for integrating xAPI tracking with SCORM Cloud. It allows you to include necessary files and scripts, such as the tincan.xml file, which SCORM Cloud uses to recognise and track your Unity WebGL build.

Note: We’ll use SCORM Cloud as an example, but you should consult your LMS’s documentation for any platform-specific requirements.

3.1 Locate and Copy the Default WebGL Template

Unity uses HTML templates to structure the WebGL build output. By default, Unity provides a basic template, which you can customise to suit your needs. Here’s how you can create a custom template:

  1. Locate the Default WebGL Template:
    • Windows:
      • Navigate to C:\Program Files\Unity\Hub\Editor\<Your Unity Version>\Editor\Data\PlaybackEngines\WebGLSupport\BuildTools\WebGLTemplates\.
    • Mac:
      • Go to /Applications/Unity/Hub/Editor/<Your Unity Version>/PlaybackEngines/WebGLSupport/BuildTools/WebGLTemplates/.
  1. This directory contains the default templates that Unity uses for WebGL builds.
  2. Copy the Default Template Folder:
    • Find the Default folder within the WebGLTemplates directory.
    • Copy this Default folder. This will be the base for your custom template.

3.2 Create a Custom Template in Your Unity Project

Once you’ve copied the default template, the next step is to set it up in your Unity project.

  1. Paste the Copied Template into Your Unity Project:
    • Navigate to your Unity project’s Assets folder.
    • Inside the Assets folder, create a new folder named WebGLTemplates (if it doesn’t already exist).
    • Paste the copied Default template folder into the Assets/WebGLTemplates/ directory.
    • Rename the pasted folder to something meaningful, such as SCORMTemplate.

Your folder structure should now look like this:


Assets/
└── WebGLTemplates/
    └── SCORMTemplate/
        └── index.html
        └── ... (other template files)


Custom Template Hierarchy
Custom Template Folder View

3.3 Modify the index.html File

The index.html file within your custom template folder is crucial because it controls how your Unity WebGL build is presented in the browser.

  1. Open the index.html File:
    • Inside your SCORMTemplate folder, locate the index.html file.
    • Open this file in a text editor like Visual Studio Code, Sublime Text, or even Notepad.
  1. Ensure Compatibility with xAPI:
    • While editing the index.html, ensure that it properly loads your Unity WebGL content and includes any scripts or code necessary for initializing xAPI tracking. This includes referencing the tincan.xml file and any JavaScript needed to interface with the SCORM Cloud LRS.
  1. Ensure that your index.html properly includes any JavaScript libraries required for xAPI communication, such as the TinCanJS library, if needed by your LMS.

3.4 Add the tincan.xml File

The tincan.xml file defines the launch mechanism and activity IDs for your xAPI package, which some LMS platforms require to correctly track xAPI statements.

  1. Create the tincan.xml File:
    • Inside your SCORMTemplate folder, create a new file named tincan.xml.
  1. Define the tincan.xml Structure:
    Open the tincan.xml file in your text editor and paste the following XML structure:

<?xml version="1.0" encoding="utf-8" ?>
<tincan xmlns="http://projecttincan.com/tincan.xsd">
    <activities>
        <activity id="http://yourdomain.com/activities/your-activity-id" 
type="http://adlnet.gov/expapi/activities/course">
            <name>Your Activity Name</name>
            <description lang="en-GB">A description of your activity that 
includes xAPI tracking.</description>
            <launch lang="en-GB">index.html</launch>
        </activity>
    </activities>
</tincan>
  1. Modify the XML: Replace the placeholders with your specific information:
    • yourdomain.com: Your domain name.
    • your-activity-id: A unique identifier for your activity.
    • Your Activity Name: The name of your activity.
    • A description of your activity…: A description that details what your activity entails.
    • Ensure the launch tag points to the index.html file that will be generated by Unity.

3.5 Select the Custom Template in Unity

Now that your custom template is ready, you need to tell Unity to use it when building your project.

  1. Open Unity and Go to Project Settings:
    • In Unity, navigate to Edit > Project Settings.
  1. Select the Custom Template:
    • In the Project Settings, go to the Player settings under the Resolution and Presentation tab.
    • Find the WebGL Template dropdown menu.
    • Select your custom template (SCORMTemplate).
Resolution and Presentation Settings

3.6 Building Your Unity Project with the Custom Template

  1. Build Your Project:
    • Go to File > Build Settings in Unity.
    • Select WebGL as the target platform.
    • Click Build and choose a location to save your build.
  1. Verify the Build:
    • After building, verify that the output directory contains the necessary files, including the index.html and tincan.xml within your custom template folder.

4. Packaging and Uploading Your Unity WebGL Build to the LMS

In this section, we’ll guide you through the process of packaging your Unity WebGL build, uploading it to SCORM Cloud, and ensuring that xAPI statements are correctly sent and logged.

Note: We’ll use SCORM Cloud as an example, but the general principles apply to other xAPI-compliant LMS platforms.

4.1 Building and Packaging Your WebGL Build

  1. Build Your WebGL Project:
    • In Unity, go to File > Build Settings.
    • Select WebGL as the platform.
    • Ensure that your custom template, which includes the tincan.xml file, is selected under Player Settings > Resolution and Presentation > WebGL Template.
    • Click on Build and choose a folder to save your WebGL build (e.g., Builds/WebGL).
  1. Verify the tincan.xml File:
    • After the build process is complete, navigate to the folder where the build was saved.
    • Ensure that the tincan.xml file is present in the root directory of your WebGL build folder, alongside the index.html file.
  1. Compress all the contents inside your build folder (not the folder itself) into a .zip file:
    • Select all the contents of your build folder (including index.html, Build folder, TemplateData folder, and tincan.xml).
    • Right-click and choose Send to > Compressed (zipped) folder to create a .zip file. This will be the package you upload to SCORM Cloud.

4.2 Uploading to SCORM Cloud

Upload the Package to Your LMS: Most LMS platforms have an option to import or upload a course package. Navigate to this section in your LMS dashboard. For example, in SCORM Cloud:

  1. Log in to SCORM Cloud:
  1. Upload the Course Package:
    • Navigate to the Library section in the SCORM Cloud dashboard.
    • Click on Import Course and upload the .zip file containing your WebGL build.
    • Provide a Course ID if you want to specify one; otherwise, leave it blank to have one generated automatically.
    • Click Import to upload your course to SCORM Cloud.
Add Content Dialogue
Upload xAPI Dialogue
  1. Verify the Upload:
    • After the course is uploaded, it will appear in your SCORM Cloud library.
    • Click on the course to preview it and ensure everything is functioning as expected.

4.3 Viewing xAPI Statements in SCORM Cloud

After users interact with your WebGL game, you can view the xAPI statements that were sent to the LRS. Statements usually appear in the LRS Viewer within a few minutes after the interaction, allowing you to quickly verify and analyze user data. In your LMS dashboard, find the section for viewing xAPI statements or learning records. This may be labeled differently depending on your LMS (e.g., ‘LRS Viewer’, ‘Reports’, ‘Analytics’). For example, in SCORM Cloud:

  1. Access the LRS Viewer:
    • In the SCORM Cloud dashboard, go to the LRS (Learning Record Store) section.
    • Click on LRS Viewer to view the xAPI statements.
  1. Filter and Search Statements:
    • Use filters to search for specific statements by actor, verb, or activity.
    • You should see statements corresponding to the interactions in your WebGL game, such as “completed” or “experienced.”
LRS Viewer Page

4.4 Creating a Public Invitation Link

To allow others to access your course, SCORM Cloud lets you create public invitation links:

  1. Create an Invitation:
    • In SCORM Cloud, navigate to the Invitations section.
    • Click on Create Invitation and select the course you want to share.
  1. Configure the Invitation:
    • Choose whether the invitation will be public or private. Public invitations can be accessed by anyone with the link, while private ones require an email address.
    • Set any other desired options, like a maximum number of uses or an expiration date.
  1. Share the Invitation Link:
    • After creating the invitation, SCORM Cloud will generate a unique link.
    • Share this link with your intended audience.
  1. Testing the Public Link:
    • Open the link in an incognito window or another browser to ensure it works as expected.
    • Complete the course yourself to verify that xAPI statements are being recorded in the SCORM Cloud LRS Viewer.
Invitation Dialogue

By following these steps, you can successfully upload your Unity WebGL build to SCORM Cloud, create accessible links for users, and track their interactions through xAPI.

Conclusion

Hosting a Unity WebGL build on an LMS with xAPI tracking provides a powerful way to monitor and report user interactions in serious games, training simulations, or educational experiences. By following this guide, you’ve learned how to set up your LMS environment, integrate xAPI into your Unity project using a custom script, create a custom WebGL template for xAPI compatibility, and package and upload your build to the LMS.

The process allows you to leverage the Learning Record Store (LRS) capabilities of your chosen LMS to gather detailed insights into user behaviour, such as course completions and other significant interactions. This data is invaluable for understanding how users engage with your content and improving your courses based on real-world feedback.

By setting up public invitations or access links, you can easily share your courses with a wide audience, ensuring that your educational content is accessible and trackable. Whether you’re an educator, a corporate trainer, or a game developer, this integration empowers you to create more engaging and accountable learning experiences.

Now that your Unity WebGL build is live on your LMS, you can monitor xAPI statements, refine your content, and continue to innovate in delivering interactive learning experiences. Take advantage of your LMS’s LRS features to explore more complex tracking scenarios, integrate with other systems, or expand your reporting capabilities. With the foundation provided by this guide, you’re well-equipped to further customise and optimise your content to maximise its impact in learning and training environments.

Note: While we’ve used SCORM Cloud as an example throughout this guide, the principles and steps outlined are applicable to any xAPI-compliant LMS. Always refer to your specific LMS’s documentation for detailed instructions.

We hope this guide has provided valuable insights for hosting your Unity WebGL builds with xAPI tracking. If you’re interested in exploring more about our experiences and expertise in e-learning and game development, follow this link here to learn more.

Are you looking to implement custom Unity WebGL solutions for your organization? At Sliced Bread, we specialise in creating engaging learning experiences and have extensive expertise in developing interactive content. Contact us today to discover how we can assist you with your project!

Recent Posts