October 3, 2013

Because PHP will be executed long before this function is called, we can use PHP to write information directly into the function. You could grab this information other ways with another server side language, or even by making Ajax requests from the jQuery version that Unity already loads. Here is an example of a PHP dependent function we add to our modified template:

function Initiate()
{

 var response = {};
 response.hostname = "<?php echo $hostname ?>";
 response.authenticated = "<?php echo $authenticated; ?>";
 response.existence = "<?php echo $existence ?>";
 response.offlinePlay = "<?php echo $offline_play ?>";

 u.getUnity().SendMessage("Manager", "ServerResponse", JSON.stringify(response));
}

Here we assign properties to our response object that will be passed back to Unity. We are telling it what server to talk to, if we think they are logged in, if they have saved data, and if this game should be available for offline play. These are just a few of the possible values the app might care about. The last line is a little cryptic, but we’ll explain that later.

This script assumes that several PHP variables have been declared. We are using a controller in our PyroCMS to pass these variables to the template. Depending on what your site is built on, you might need to seek out these values before this function is rendered. We are using strings for all of this information, since our JSON parser coerces them to strings later on anyway.

We are able to call Unity this way because the u variable should have been initialized as a UnityObject2 object in the <build_name>.html file. The SendMessage call relies on a GameObject with the name Manager existing in the current scene, and sends a message to a function called ServerResponse. We like to use a static manager as a central point that provides an internal API with references to components, like our web component.

It’s a good idea to keep any private information out of this function as it can be easily overridden before ever being called. We only include things that reduce the user’s time in the menu system before getting to their destination, and hijacking this would just lead to dead ends.

If you wanted to really simplify this part, and maximize the ability to get game specific data form the server, you might just make Initiate perform an Ajax request to some game specific endpoint.