docs.unity3d.com
    Show / Hide Table of Contents

    JavaScript API for WebGL User Guide

    This section describes how you can set up your HTML page containing a WebGL build so that it can access the JavaScript API. It also describes the events, properties, and methods you can use to interact with the Unity Forma configurator. For information on how to enable the JavaScript API in your project, see JavaScript API for WebGL.

    Accessing Unity Forma from the containing page

    This information assumes that you use the default WebGL template for the build and there is a script section on the page where a Unity instance is created. A call to createUnityInstance creates the instance on the page. It returns a promise that resolves to the instance that is created.

    Using the instance (called unityInstance by default), you can access Unity Forma using unityInstance.Module.forma. To make it so that Unity Forma can be accessed outside the scope of this callback, you must create a variable that is global to the HTML page.

    The code should appear as follows:

    <script>
    
        //...
    
        let forma = null; // <-- code to be added
    
        var script = document.createElement("script");
        script.src = loaderUrl;
        script.onload = () => {
            createUnityInstance(canvas, config, (progress) => {
                progressBarFull.style.width = 100 * progress + "%";
         }).then((unityInstance) => {
            forma = unityInstance.Module.forma; // <-- code to be added
            // ...
         }
    
         //...
    
     </script>
    

    Once Unity Forma is accessible, we can listen to events and call methods to make changes in the configurator.

    Events

    The JavaScript API exposes a set of events that Unity Forma triggers. Once you create a forma global variable, any JavaScript code in the containing page can listen to events using forma.addEventListener(<<eventname>>, <<callback>>);. For example:

    const handleProductChanged = (e) => {
        //...
    };
    forma.addEventListener(forma.productChanged, handleProductChanged);
    

    To stop listening to an event, we must call removeEventListener. The following example uses the callback we defined above:

    forma.removeEventListener(forma.productChanged, handleProductChanged);
    

    You can provide the event names in string format (such as productChanged), but to minimize errors and make it easier to change event names, Unity Forma provides properties that return the event names. You can access them from forma.eventname.

    The events, properties and methods below assume that a global variable named forma points to the instance of the JavaScript Forma class. If the variable has a different name, you must replace forma with that name.

    Available events

    forma.configuratorEnabled

    This event is triggered when the Unity Forma Configurator object has been initialized and is ready to use. Listening to this event is mandatory since no call to any API method should be done before this is received.

    Parameters

    None.

    forma.productChanged

    This event is triggered when the product has changed. If you want to build a custom UI that will not always be initialized before this event is triggered, you must make sure that you build the UI so that it can handle this situation.

    Parameters

    The 0-based index of the new Configurator product, accessed using the index property of the event parameter. Can be null.

    forma.configurationChanged

    This event is triggered when the configuration of the product changes after a change request.

    Parameters

    None.

    forma.rulesChanged

    This event is triggered when the rules change, such as when a feature is no longer available when a different feature is selected.

    Parameters

    None.

    forma.featureSetListChanged

    This event is triggered when a request to fetch the list of feature sets (an asynchronous operation) returns, or when another operation causes the list of feature sets to refresh.

    Parameters

    A list of DisplayInfo objects, accessed using the featureSets property of the event parameter. This list can be empty, but not null.

    forma.featureListChanged

    This event is triggered when a request to fetch the list of features (an asynchronous operation) returns, or when another operation causes the list of features to refresh.

    Parameters

    A list of DisplayInfo objects, accessed using the features property of the event parameter. This list can be empty, but not null.

    forma.environmentChanged

    This event is triggered when the environment changes. If you want to build a custom UI that will not always be initialized before this event is triggered, you must make sure that you build the UI so that it can handle this situation.

    Parameters

    The id of the new Configurator environment, accessed using the id property of the event parameter.

    forma.cameraChanged

    This event is triggered when the camera changes.

    The id of the new Configurator camera, accessed using the id property of the event parameter. The id of the new Configurator environment, accessed using the id property of the event parameter.

    forma.contextChanged

    This event is triggered when the context changes.

    Parameters

    None.

    forma.pricingChanged

    This event is triggered when the pricing information of the product changes.

    Parameters

    A JSON object that contains the new pricing information, accessed using the pricing property of the event parameter.

    The returned object has the following format:

    {
        value, //(true or false)
        totalPrice //string containing the currency
    
        featurePrices: [ //list of the features and their associated pricing information
            {
                id, //the code to identify the feature
                price //string containing the currency
            },
            //...
        ]
    }
    

    forma.isLoadingChanged

    This event is triggered when the loading state of the application changes. You can use it to display a loading screen and block user input while a loading operation is in progress.

    Parameters

    A boolean indicating whether or not the application is currently loading, accessed using the isLoading property of the event parameter.

    Methods

    The JavaScript API exposes several methods that you can use to manipulate the Forma Configurator. The methods enable operations that you typically expect from a menu. Assuming that a forma global variable already exists, any JavaScript code in the containing page can get properties or call methods using:

    const propertyValue = forma.propertyName; //properties
    
    forma.methodName(param1, param2, ...); //methods
    

    Available properties

    forma.products

    This property returns a list of strings that contain the product names. Can be empty but not null.

    forma.environments

    Returns a list of DisplayInfo objects that describe the environments. Can be empty but not null.

    forma.cameras

    Returns a list of DisplayInfo objects that describe the cameras. Can be empty but not null.

    forma.contexts

    Returns a list of contexts as a JSON object with the following format:

    {
        [
            name, //context identifier
            selection, //current value for this context
    
            values: [ //possible values for this context
                {
                    key, //identifier of this option
                    value //value of this option
                },
                //...
            ]
        ]
    }
    

    It can be empty but not null.

    forma.currentProductIndex

    Returns the 0-based index of the current Configurator product.

    forma.currentProduct

    Returns information about the current product as a JSON object with the following format

    {
        name, //product name
        description, //product description
        thumbnail, //can be rendered on a canvas. The fields are rawTexturePointer, width, height
        price //the total price of the product
    }
    

    Returns null if there is no active product.

    forma.currentEnvironment

    Returns information about the current environment as a JSON object with the following format:

    {
        id, //environment id
        name, //environment name
        thumbnail, //can be rendered on a canvas. The fields are rawTexturePointer, width, height
    }
    Returns null is there is no active environment.
    
    Return information about the current camera as a JSON object with the following forma
    
    {
        id, //camera id
        name, //camera name
        description, //camera description
        thumbnail, //can be rendered on a canvas. The fields are rawTexturePointer, width, height
    }
    

    Returns null if there is no active camera.

    Available methods

    forma.switchProduct(index)

    Switches the Configurator to the product with the specified 0-based index.

    Returns

    Nothing.

    forma.switchEnvironment(id)

    Switches the Configurator to the environment with the specified id. Will fail if the Configurator is in the process of loading a new product.

    forma.switchCamera(id)

    Switches the Configurator to the camera with the specified id. Will fail if the Configurator is in the process of loading a new product.

    forma.switchContext(key, value)

    For the current product, switches the context identified by key to the specified value.

    forma.fetchFeatureSets()

    Fetches the feature sets for the current product. Since this is an asynchronous call, this method does not return any value. If the fetch operation is successful (meaning that the application is not currently busy loading a product), the featureSetListChanged event will be triggered.

    forma.fetchFeatures(featureSetCode)

    Fetches the features of the specified feature set code for the current product. Since this is an asynchronous call, this method does not return any value. If the fetch operation is successful (meaning that the application is not currently busy loading a product or the list of feature sets), the featureListChanged event will be triggered.

    forma.getSelectedFeature(featureSetCode)

    Returns the code of the selected feature for the specified feature set code, in a string format. Can be null.

    forma.selectFeature(featureCode)

    Selects the feature with the specified code for the current product. This will fail silently if the application is currently loading a product, or expecting a result from fetchFeatureSets or fetchFeatures.

    Classes

    Forma

    The Forma class is the entry point for the JavaScript API. The code on the HTML page containing the WebGL build has access to an instance of this class, which allows listening to events as well as calling functions from Forma.

    DisplayInfo

    This class holds all values that can be used to display relevant information in the UI. The JavaScript API currently returns lists of DisplayInfo objects when invoking environments or cameras.

    Lists of DisplayInfo objects are also returned by the following events:

    • featureSetListChanged
    • featureListChanged

    DisplayInfo has the following properties:

    • id //string
      Unique identifier of the displayed element, such as a camera id.
    • name //string
      The display name of the element.
    • enabled //boolean
      Whether or not this element is currently enabled.
    • price //string
      The price of the element (including the currency symbol).
    • isToggleable //boolean
      Whether or not this element can be clicked again when already selected.

    DisplayInfo has the following method:

    • getThumbnail() //string
      Method that generates and returns a data URL that can be used for the src attribute of an HTML <img> tag.

    Note: All textures that will be displayed as thumbnails on the JavaScript side must be uncompressed.

    Helpers

    Contains static helper functions. Available functions include:

    • stringToPointer(stringValue) //
      Converts a string to an int pointer that can be sent to and used by the Forma C# code.
    • generateDataURLFromTexturePointer(rawTexturePointer, width, height)//
      Uses the raw texture pointer passed from C# as well as the width and height of the texture to generate a data URL. This data URL can then be used by the src attribute of an HTML tag.
    Back to top
    Terms of use
    Copyright © 2023 Unity Technologies — Terms of use
    • Legal
    • Privacy Policy
    • Cookies
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)
    "Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
    Generated by DocFX on 18 October 2023