October 3, 2013

Building an app for Unity’s web player is wonderfully simple. The build process returns a neatly packaged unity3d file and a sample HTML template that can immediately load the app, assuming the Unity Web Player has been properly installed. But how can we provide a better experience than a standalone app embedded in a page? Even after reading Unity’s documentation on Web Player and browser communication, it was unclear to us.

We wanted to integrate our games into a site, and we wanted the user identity to be uniform across all domains. Using this pattern, we render identity specific configuration data along with the page. This provides our games immediate access to all of the data they might need, and doesn’t require making Unity dig into cookies or hard coding server information into our builds. Another advantage is this allows us to include a basic web configuration in any of our games with a single script.

Here is a visual of our initial setup:

unityweb1

First, we define a point of contact for our application in the form of a JavaScript function on the page. We call this function Initiate, but that’s not very important. Unity can access JavaScript functions that are in the same scope via Application.ExternalCall. This is key to our task. This function will call out to Initiate, but it does not return what Initiate returns. Instead, we have Initiate make a a call using Unity’s own SendMessage function. We’ll go more in depth with this later.