As mentioned in the last post, today we’re going to have some fun pulling data fromour recently-implemented, cloud-based web-service into the Unity3D game engine.
My intention, here, is to reinforce the fact that exposing web-service APIs really does give you broader reach with your technology. In this case, we’ll be calling our web-service – implemented using F#, which we could not have included in our Unity3D project – inside a game engine that could be hosted on any one of a wide variety of operating systems.
A few words on Unity3D: according to its web-site, Unity3D is “a feature rich, fully integrated development engine for the creation of interactive 3D content.” While the main goal behind Unity3D (which from here on I’ll just call Unity) is clearly for people writing games, Unity is also a great visualization environment.
This technology is cool. It makes heavy use of .NET – perhaps not the first environment you’d think of when implementing a cross-platform game engine – but its use of Mono allows you to use it to create games for Windows, Mac, the web, Android, iOS, PS3, Wii and Xbox 360. Woah!
One of the great things about Unity is the sample content available for it. The default scene when you install Unity is called Angry Bots, for instance, which is a fully-featured third person shooter. Now I’m not actually interested in implementing a game for this post – although that might be pretty cool, shooting each of the spheres in an Apollonian packing ;-) – so I decided to start with a more architectural sample scene.
I didn’t want to make any static changes to the scene – it looks really cool as it stands – I just wanted to access the web-service, pull down the sphere definitions and then create “game objects” inside the scene dynamically at run-time.
A quick aside regarding my OS choice for this… I originally started working with the Windows version of Unity inside a Parallels VM on my Mac, but then decided to switch across to the Mac version of Unity. The scene loaded as well there as it did on Windows – nothing needed to change, at all. I installed the free version of Unity – which means I can’t build for mobile platforms or game consoles – but you can apparently get free trials of a version that builds for those environments, if so inclined.
Unity’s scripting environment is pretty familiar: the MonoDevelop editor installed with Unity is pretty decent – it was my first time using the tool, and I thought I’d give it a try rather than configuring Unity to use Visual Studio – and is well integrated with the Unity scene development environment. You can code in either Javascript or C# (no prizes for guessing which one I chose ;-), and it’s possible to have both in a scene.
I started off bringing down a JSON-reading implementation for their Wiki (be sure to add the Nullable class definition, listed further down the page) which would help me from my own code. I added an additional C# source file – which must be calledImportSpheres.cs, as it needs to match the name of the class – and placed this code in it:
using UnityEngine;
using System.Collections;
using System.Net;
using System.IO;
public class ImportSpheres : MonoBehaviour
{
// The radius of our outer sphere
const float radius = 0.8f;
IEnumerator DownloadSpheres()
{
// Pull down the JSON from our web-service
WWW w = new WWW(
"http://apollonian.cloudapp.net/api/spheres/" +
radius.ToString() + "/7"
);
yield return w;
print("Waiting for sphere definitions\n");
// Add a wait to make sure we have the definitions
yield return new WaitForSeconds(1f);
print("Received sphere definitions\n");
// Extract the spheres from our JSON results
ExtractSpheres(w.text);
}
void Start ()
{
print("Started sphere import...\n");
StartCoroutine(DownloadSpheres());
}
void ExtractSpheres(string json)
{
// Create a JSON object from the text stream
JSONObject jo = new JSONObject(json);
// Our outer object is an array
if (jo.type != JSONObject.Type.ARRAY)
return;
// Set up some constant offsets for our geometry
const float xoff = 1, yoff = 1, zoff = 1;
// And some counters to measure our import/filtering
int displayed = 0, filtered = 0;
// Go through the list of objects in our array
foreach(JSONObject item in jo.list)
{
// For each sphere object...
if (item.type == JSONObject.Type.OBJECT)
{
// Gather center coordinates, radius and level
float x = 0, y = 0, z = 0, r = 0;
int level = 0;
for(int i = 0; i < item.list.Count; i++)
{
// First we get the value, then switch
// based on the key
var val = (JSONObject)item.list[i];
switch ((string)item.keys[i])
{
case "X":
x = (float)val.n;
break;
case "Y":
y = (float)val.n;
break;
case "Z":
z = (float)val.n;
break;
case "R":
r = (float)val.n;
break;
case "L":
level = (int)val.n;
break;
}
}
// Create a vector from our center point, to see
// whether it's radius comes near the edge of the
// outer sphere (if not, filter it, as it's
// probably occluded)
Vector3 v = new Vector3(x, y, z);
if ((Vector3.Magnitude(v) + r) > radius * 0.99)
{
// We're going to display this sphere
displayed++;
// Create a corresponding "game object" and
// transform it
var sphere =
GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphere.transform.position =
new Vector3(x + xoff, y + yoff, z + zoff);
float d = 2 * r;
sphere.transform.localScale =
new Vector3(d, d, d);
// Set the object's color based on its level
UnityEngine.Color col = UnityEngine.Color.white;
switch (level)
{
case 1:
col = UnityEngine.Color.red;
break;
case 2:
col = UnityEngine.Color.yellow;
break;
case 3:
col = UnityEngine.Color.green;
break;
case 4:
col = UnityEngine.Color.cyan;
break;
case 5:
col = UnityEngine.Color.magenta;
break;
case 6:
col = UnityEngine.Color.blue;
break;
case 7:
col = UnityEngine.Color.grey;
break;
}
sphere.renderer.material.color = col;
}
else
{
// We have filtered a sphere - add to the count
filtered++;
}
}
}
// Report the number of imported vs. filtered spheres
print(
"Displayed " + displayed.ToString () +
" spheres, filtered " + filtered.ToString() +
" others."
);
}
void Update ()
{
}
}
There’s nothing earth-shattering about this code: it calls our web-service to pull down a fairly detailed (level 7) representation of an Apollonian packing and inserts the resultant spheres into the current scene.
The code makes use of some Unity-specific classes, such as WWW – rather than some standard .NET capabilities which proved a bit more problematic – and there were some quirks needed to implement “co-routines” from C# (which meant having to return an IEnumerator and use yield return).
Being based on Mono, your Unity code is always going to be a bit behind the state-of-the-art in the latest .NET Framework, but hey – that’s the cost of being cross platform. :-)
Otherwise, it’s probably worth mentioning that the code only adds GameObjects for spheres that are close to the outside of the outer sphere, as they would only end up being occluded, anyway.
After the script has been added to the scene – in this case in the _Scripts folder – it’s a relatively simple matter of attaching it to one of the scene’s objects, to make sure it gets called. This step took me some time to work out – despite it being really simple, once you know how – so I’ll step through it, below.
From the base scene with our scripts added…
We just need to select a game object (in this case I chose the computer desk, but we could select anything in the initial scene), and then choose Component –> Scripts –> Import Spheres.
Once this has been selected, we should be able to see the script attached to the selected object in the Inspector window on the right. This means the script will be executed as the game object – and as a static object this ultimately means the scene – loads.
The script will be checked, by default – to stop it from running you can either uncheck it or use the “cog” icon to edit the script settings and select “Remove Component” to get rid of it completely.
Now we can simply run the scene using the “play” icon at the top – which runs the scene inside the editor – or you can build it via the File menu and run the resultant output.
Here’s the scene in the editor:
I tried embedding the Unity web player in this post, directly, but gave up: it seems you need to edit the <head> section of your HTML page to load the appropriate script: I could do that for every post on this blog, but that seems like unnecessary overhead. If you’d like to give the scene a try, you’ll have to open a separate page to do so.
Once small note: I did need to add a crossdomain.xml file to our Azure-hosted ASP.NET web-service, to make sure it met with Unity’s security requirements.
Right – that’s it for today’s post. Next time we’ll be continuing to look at using our data in other places, as we shift gears and implement a basic 3D viewer for the Android platform.
原文 http://through-the-interface.typepad.com/through_the_interface/2012/04/calling-a-web-service-from-a-unity3d-scene.html