Calling a web-service from a Unity3D scene

转载 2013年12月04日 15:28:19

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(

      "" +

      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





  void Start ()


    print("Started sphere import...\n");





  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)



    // 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;


          case "Y":

            y = (float)val.n;


          case "Z":

            z = (float)val.n;


          case "R":

            r = (float)val.n;


          case "L":

            level = (int)val.n;





        // 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




          // Create a corresponding "game object" and

          // transform it


          var 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 =;


          case 2:

            col = UnityEngine.Color.yellow;


          case 3:

            col =;


          case 4:

            col = UnityEngine.Color.cyan;


          case 5:

            col = UnityEngine.Color.magenta;


          case 6:

            col =;


          case 7:

           col = UnityEngine.Color.grey;



          sphere.renderer.material.color = col;




          // We have filtered a sphere - add to the count







    // Report the number of imported vs. filtered spheres



      "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…Our initial scene with our two 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.

Attaching our script to a game object

Our script attached to the object in the InspectorOnce 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:

Our Apollonian Apartment in action

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.



好吧,最近开始在Asset store上面下资源看别人做的demo了,发现一个问题是我要在animation窗口编辑一个clip,却死活编辑不了一个prefab对象,只能看,后来在网上找了半天也没找到...


【Unity3D】RPG黑暗之光Scene1:创建开始场景 1、导入资地形、地貌资源,新建场景,导入地形、地貌prefab,设置相机位置,添加全局灯光。 2、设置鼠标指针图片: Edit-->P...

Unity3D说明文档翻译-Scene View Control Bar

Scene View Control Bar 场景视图控制栏 The Scene View control bar lets you choose various options for view...

Unity3D开发(三):场景管理插件Scene Manager

Unity3d中提供了场景Scene的概念,Scene就是一组相关联的游戏对象的一个集合,通常每个集合就是一个场景,但是也有可能只是一个场景的一部分! 场景中的游戏对象是任意的,可以是HUD的UI组件...

添加启动游戏过渡场景Default Splash Scene(Unity3D开发之十三)

添加启动游戏过渡场景Default Splash Scene(Unity3D开发之十三)Unity5个人版会添加Unity Logo作为启动画面,咱们既然没花钱,打个广告也应该。但Unity Logo...


【Unity3D实战】RPG黑暗之光Scene2:创建角色选择场景 1、开始角色创建场景,导入模型和UI资源: 导入模型和角色UI相关的资源。 拷贝一份start场景,重命名为chara...


【Unity3D实战】RPG黑暗之光Scene3:创建游戏运行场景及角色控制 1、创建场景: 基于上一个场景做一份拷贝,删除UI Root下的所有组件(除Camera外)。删除Charac...

Unity3D说明文档翻译-Scene View Navigation

Scene View Navigation 场景视图导航 The Scene View has a set of navigation controls to help you move arou...



Unity3D——MonoBehaviour api函数 调用时序剖析(From 圣典)

MonoBehaviour Mono行为 Inherits from Behaviour MonoBehaviour is the base class every script derives f...
  • jscese
  • jscese
  • 2015年10月27日 10:06
  • 2209
您举报文章:Calling a web-service from a Unity3D scene