Calling a web-service from a Unity3D scene

为Unity搭建Web服务器 在Win7下搭建 Web服务器 1. 下载并安装Apache https://httpd.apache.org/download.cgi 运行httpd-2.2.22-win32-x86-openssl-0.9.8t.msi 2. 设置Web路径 比如需要将 E:/Work/Web 作为Web的根路径 打开 C:\Program Fi 阅读详情

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…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.


原文 http://through-the-interface.typepad.com/through_the_interface/2012/04/calling-a-web-service-from-a-unity3d-scene.html


RESTful-Unity:RESTful-Unity旨在为Unity3d提供一个简单的RESTful HTTP服务器 RESTful统一 RESTful-Unity旨在为提供一个简单的RESTful HTTP服务器。 通过http请求从Unity场景访问并封装游戏对象的状态。 这个项目是在3D原型制作原型期间创建的,其中可以通过访问和控制游戏对象。 这是概念验证项目,因此服务器的功能保持在最低限度。 GET范例用于请求游戏对象的颜色。 路径:/ color / {游戏对象名称} 开机自检示例用于通过POST请求更改游戏对象的颜色。 路径:/ color / {游戏对象名称} 产品特点 支持的HTTP类型:GET,POST,PUT和DELETE 在配置类中存储和配置路由 创建参数化路由路径 从请求访问 立即下载

相关推荐

详谈Unity3D利用Webservice读取数据库(菜鸟版)

详谈Unity3D利用Webservice读取数据库(菜鸟版)

A18:Unity3d搭建与调用webservice方法

1、在unity安装目录下进入F:\Unity5.2.2\Unity\Editor\Data\Mono\lib\mono\2.0,在这个目录中找到两个dll分别为system.web.dll、system.web.services.dll,将这两个dll文件拖拽进入unity中的Plugins文件夹下(没有Plugins文件夹请在asset目录下创建)。 2、打开visual studio...

. 3142

Unity访问WebService个人用

Unity访问WebService个人用

完整mes代码(含客户端和server端_ET框架1:C#服务器 unity3d客户端 开源 github

这段时间做了个项目,虽然是VR项目,不是游戏,但是用到了多人游戏的机制,因为是小项目就想服务器和客户端都自己搞定吧,节省人力物力。终于功夫不负有心人,找到了满意的框架:ET框架,绝逼好用的框架,最大特点:1 C#服务器,unity3d客户端,前后端一个人就搞定了,节省了沟通,物质成本。2 服务端采用组件式框架实现了分布式服务器架构。3 可以让客户端人员更好的理解服务器,服务器开发人员更好的理解客户...

weixin_39797324的博客 2582

Unity3D访问Webservice返回的数据集并解析

Unity3D访问Webservice返回的数据集并解析

【AI方案集】AI与人机协作相结合的智能法律咨询系统.docx

AI技术方案以算力、算法、数据三角协同为核心,通过搭建标准化的数据预处理、模型训练与边缘云端协同部署流程,将计算机视觉、自然语言处理、机器学习等核心能力深度融入业务场景,既实现自动化流程降本提效,又通过精准的模式识别与预测分析为管理层提供数据驱动的决策支撑,最终完成从通用AI技术到行业定制化场景的适配落地,为企业数字化转型提供可落地的技术路径。

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 because of a template argument mismatch. You are calling fmod with a floating point argument an

愿世界和平的IT劝退师 8696

MobaXterm终端工具个人学习版安装包及常用配置备份

资源包含 MobaXterm 个人版的安装包以及日常运维常用的基础配置备份文件。适用于网络工程师及运维人员用于日常的服务器管理、SSH 连接及串口调试。 压缩包内附带了个人整理的软件使用技巧与配置说明(仅供个人学习参考)。请各位同行下载后注意,技术工具请尽量支持官方正版,本资源仅供个人测试与交流使用,切勿用于商业环境。

aiohttp 高并发web服务_UE4 unity3d连接高并发http服务器

1、HTTP服务器使用c++语言开发,vs2019编辑器。支持windows和linux。服务器主要用于游戏服务器后台,以及APP 应用后台增、删、查、改数据。 2、服务器使用多线程技术,以及使用线程池,有工作任务就及时处理,没有工作任务就处于休眠状态。线程之间通信使用锁机制,主线程主要做新的连接统一管理,有新的连接统一派发通知各个工作线程处理,主线程撒也不干就主要做分派工作。 ...

weixin_35315019的博客 305

机械臂的「抽风」自救指南:从万向节死锁到毫米级丝滑抓取

机械臂的「抽风」自救指南:从万向节死锁到毫米级丝滑抓取

科技中介服务机构如何借助平台提升技术撮合服务的专业性与响应速度?.docx

科易网基于AI模型+行业大数据,在技术转移、成果转化、技术经纪、知识产权、产业创新、科技招商等垂直领域的多样化应用场景,推出科技创新领域的AI+工具与数智化解决方案,推动科技创新与产业创新智能化发展。

SpringAop@Pointcut切点调用不到嵌套方法分析

切入点和通知 package spring.pointcut; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; @Aspect public class TargetMonitor { //

奔跑的菜鸡 2176

产业园区如何利用AI技术提升科技成果转化服务的响应速度与转化成功率?.docx

科易网基于AI模型+行业大数据,在技术转移、成果转化、技术经纪、知识产权、产业创新、科技招商等垂直领域的多样化应用场景,推出科技创新领域的AI+工具与数智化解决方案,推动科技创新与产业创新智能化发展。

Unity3D利用Webservice读取数据库

相信大家从事Unity3D开发的,无论是做单机的还是做网游的,特别是稍微大点的项目,都会用到数据库,但是网络上关于Unity3D如何连接数据库的教程少之甚少,搜来搜去无非是那篇Unity3D如何连接mysql数据库,而且是一种直连的方法,即在Unity3D端直接连接数据库并对数据库进行操作。这样的方法有很多弊端,具体这里不说,而且我们也应该把这种直连的方法抛弃。那么Unity3D如何连接数据库?用...

qq_30279553的博客 1027

11232131231231是的

11232131231231是的

工业相机TEC散热技术:从原理到高精度成像的实战解析

本文深入解析了工业相机TEC散热技术的核心原理与实战应用。通过阐述热电制冷器如何利用帕尔帖效应实现精准温控,有效抑制图像传感器暗电流噪声,从而保障高精度成像的稳定性。文章结合工业场景痛点,提供了从TEC选型、系统集成到控制逻辑的完整设计指南,并分享了不同应用场景下的实战案例,是提升工业视觉系统成像质量的关键技术解析。

weixin_29269441的博客 412

Unity3d PC 发布遇到的问题

此功能是实验功能,勾选上后,有时功能不会相应。建议不勾选

yuyingwin的专栏 2547

普通人也能看懂的Transformer源代码解释(PyTorch)

Transformer源代码解释之PyTorch篇 章节 词嵌入 位置编码 多头注意力 搭建Transformer 在这里插入图片描述 词嵌入 Transformer本质上是一种Encoder,以翻译任务为例,原始数据集是以两种语言组成一行的,在应用时,应是Encoder输入源语言序列,Decoder里面输入需要被转换的语言序列(训练时)。一个文本常有许多序列组成,常见操作为将序列进行一些预处理(如词切分等)变成列表,一个序列的列表的元素通常为词表中不可切分的最小词,整个文本就是一个大列表,元素为一个一

qq_50974223的博客 4167
上一篇: mybatis 联合主键一对多
下一篇: 移动互联网长连接方案实例
ppby2002
博客等级 码龄23年 65粉丝 104原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值