Consuming a WCF Service from Unity3D

Unity3D is running MONO.Net and WCF implementation was for some time being worked on under “Moonlight 3.5” for MONO.  It has been merged into the main distribution of MONO for a while now; and yes, Unity3D supports it.  I will assume if you are reading this, you know how to create and host WCF services so I will not touch that at all.

Assumption: You have a WCF service running on your local IIS server at: http://localhost:8080/MyService.svc

There are a few infrastructural steps involved on the Unity3D side:

  • Setting API compatibility
  • Add plugins to project tree
  • Generate and add client proxy
  • Add gateway specific to the Unity3D application

Setting API compatibility

By default, Unity3D uses a stripped down version of the MONO framework.  You can consider this similar to .Net 4.0’s Client Profile versus Full version.  This setting can be changed through the menu bar: Edit -> Project Settings -> Player.  It needs to be set to 2.0 and not 2.0 Subset.

Add plugins to project tree

Unity3D’s runtime will enumerate a specific folder for assemblies and make those references available to the scripting engine “globally”.  At the root level, simply create “Plugins”.  Any assembly you package and use as a business layer should be deployed here.

In the new container folder, you need to add the MONO assembly compilations for the standard WCF assemblies you’d normally use in a Microsoft .Net Framework runtime.  Navigate to your Unity3D installation directory and start diving into the mono 2.0 location (for a point of reference, mine is: C:\Program Files (x86)\Unity\Editor\Data\Mono\lib\mono\2.0).

You will need to copy three assemblies into the Plugins container:

  • System.Runtime.Serialization
  • System.Security
  • System.ServiceModel

Generate and add client proxy

Add another container named “ClientProxies”.  This can technically be nested under “Scripts” or whatever folder convention / structure you may have or desire (Plugins is the only engine specific folder).  Now run the Visual Studio Command Prompt and navigate to the ClientProxies folder (this will have the generated proxy code placed here automatically, you can alternatively generate it anywhere on your filesystem and move/copy it into this container).  Generate the proxy class using SVCUTIL

svcutil -out:MyServiceClient.cs http://localhost:8080/MyService.svc?wsdl

This will generate the same files that get created when adding a Web Service reference through Visual Studio.

Add gateway specific to the Unity3D application

Now all that remains is writing a gateway script that will use the newly created client proxy as an object and execute methods off the service.  You do this the same as any ofther WCF in-code call.  You will access to the MyServiceClient object type now, and can pass in the endpoint and binding information through the constructor.

Thats all!

Advertisements