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.


Unity3D之Web Player与unity的互相传值交互

Web Player是Unity3d自带的一个Web端插件。它可以作为普通的网站来用也可以与Unity3d进行交互。 现在先讲unity传向Web player的方法。非常简单只有一句代码: App...
  • alayeshi
  • alayeshi
  • 2016年03月07日 18:40
  • 4741

unity3d js 和web js的区别

unity中的js与其说是js,不如说是Unity Script。unity中的js是会经过编译的,其性能和本地速度差不多。在官方教材《unity 4.x从入门到精通》中unity称C#,Boo,JS...
  • konglingbin66
  • konglingbin66
  • 2016年03月31日 15:39
  • 2461


Web服务器可以做什么? 1 页游呀。 2.移动平台上面的网游, 因为移动平台的网游大多属于非实时性,所以一般都使用的是基于http协议的web方式。 3.移动平台上单机游戏的功能开关,iTun...
  • pizi0475
  • pizi0475
  • 2015年07月15日 10:55
  • 1171


介绍一下UNITY3D与WEB交互的方法,包含传入和传出 通过web,url传入数值的方法: 代码: var version : int = 1; function Check...
  • java211
  • java211
  • 2013年04月15日 16:31
  • 2238

unity中的web player与webGL

unity开发网页游戏,发布的时候可以选择web player跟webGL。unity5.4版本以后发布只能选择webGL,web player能用的最高版本是5.3.8。两者比较如下: Web ...
  • peter_teng
  • peter_teng
  • 2017年07月10日 16:52
  • 3379

Unity5 与Web详细讲解

unity WebPlayer 1.1Html中嵌入unity 内容 1.2UnityObject2.js在html中的引用关系 1.3自定义webplayer加载场景 1.4设置webplayer...
  • liuran128
  • liuran128
  • 2016年01月05日 02:47
  • 2210


  • 2017年08月26日 14:42
  • 6.86MB
  • 下载

calling a __host__ function("_wassert") from a __global__ function is not allowed错误

今天在调试代码的时候碰到一个错误:calling a __host__ function("_wassert") from a __global__ function is not allowed 。...
  • suda072605
  • suda072605
  • 2014年04月17日 17:30
  • 2263

calling a __host__ function("XXX") from a __global__ function is not allowed

原因一: error : calling a __host__ function("fmod ") from a __global__ function This is happening be...
  • u014800094
  • u014800094
  • 2017年01月06日 09:17
  • 450

unity webPlayer

本文来自: 一、Unity Web Player的下載 為了讓玩家可以在瀏覽器上執行Unity製作的網頁遊戲,U...
  • xy849288321
  • xy849288321
  • 2014年03月21日 10:09
  • 3328
您举报文章:Calling a web-service from a Unity3D scene