How to call WCF Service in unity3d

In this tutorial, I will explain how to call WCF service in unity3d engine. First let’s create a simple WCF service and host in the console application. You can choose other hosting options also for WCF service, like IIS hosting.

IDE/Engine used for this project: Visual studio 2012 professional edition, unity 5.3.2f Personal Edition

Create a WCF service:

  • Create a new project in visual studio. Select WCF template and create a WCF Service Library project. Write the project name as “WcfDemo”.
    wcf-0
  • Once the project will be loaded, select IService1.cs file and edit the code as following:
  • Change Service1.cs as following:
  • Add another project in the “WcfDemo” solution. This project will be a console application and will be named as “Host”.
    wcf-2
  • Provide reference of “WcfDemo” WCF project in “Host” console application.
  • Open configuration file app.config in “Host” project and edit the code as following:
  • Change the code of program.cs in host project as following:
  • Set “Host ” as startup project and run the application. You will get output like this.
    console
  • If you get error about “can’t access 8080 port” then close the visual studio and run it again as administrator.
  • Open “http://localhost:8080/” in browser, make sure “Host” application is running, then a page will open like this:
    wcf-wsdl
  • Here you can see which service is running over port 8080. Click on the link next to svcutil.exe, it will open an xml file in browser. This URL will be used to generate proxy class for the running service.

Call WCF service in unity3d:

  • To call WCF service in unity3d, first proxy class of the WCF service needs to be generated. To generate proxy class, we will use svcutil tool. To use this tool, go to you unity installed directory and follow the path “../Editor/Data/Mono/lib/mono/2.0”. In this directory you will find svcutil.exe file.
  • Open command window as an administrator, navigate directory path as mentioned in previous step and run the following command –
                                  svcutil -out:WcfDemoServiceClient.cs http://localhost:8080/?wsdl
    Make sure the WCF service URL is correct in command line. This command will generate “WcfDemoServiceClient.cs” file in the same directory where svcutil tool is present. This generated file will be the proxy class for WCF service in unity.
  • Change the Mono compatibility setting in Unity. Go to your Player Settings (File -> Build Settings -> Player Setting), expand “other Settings” and set “API Compatibility Level” to .NET 2.0.
  • Create a new folder in Assets directory under project hierarchy named as “Plugin” in unity editor. Copy “System.ServiceModel.dll” from “../Editor/Data/Mono/lib/mono/2.0” path and paste it in the Plugin folder.
    dll
  • Create “Script” folder in Assets directory under project hierarchy. Copy “WcfDemoServiceClient.cs” in Script directory.
    client
  • Create a new script file in “Script” directory named as “callService.cs”. Create an empty game object in scene and add this script to this empty game object. Edit “callService.cs” as following –
  • Run unity and you will see console output as – output

That’s it for this tutorial – call WCF service in unity3d. Please post your comments, if you have any question. Thanks!

Share Button
The following two tabs change content below.
Gyanendu Shekhar is a technology enthusiast. He loves to learn new technologies. His area of interest includes Microsoft technologies, Augmented reality, Virtual reality, unity3d and android development.

Gyanendu Shekhar

Gyanendu Shekhar is a technology enthusiast. He loves to learn new technologies. His area of interest includes Microsoft technologies, Augmented reality, Virtual reality, unity3d and android development.

35 thoughts on “How to call WCF Service in unity3d

  • June 1, 2016 at 9:37 pm
    Permalink

    Every Async method generated by my WCF service is causing a problem. I get multiple errors –
    “Error 4 – The type or namespace name Tasks' does not exist in the namespace System.Threading’. Are you missing an assembly reference?”

    Reply
      • June 3, 2016 at 12:10 am
        Permalink

        The references to System.Threading are in the generated proxy class. I’m not sure how to fix this.

        Reply
        • June 3, 2016 at 1:36 am
          Permalink

          Unity3d supports .NET 2.0 and for System.Threading.Tasks classes .NET3.5 is required. That may be the problem. To avoid unsupported classes for unity in your WCF proxy class, make sure you use svcutil.exe tool from unity3d installed directory only. I mentioned this in the first step of “Call WCF service in unity3d” section in the article. If your unity3d is installed in “C:\Program Files” then svcutil.exe location will be “C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0”. Don’t generate proxy class from Visual studio developer command prompt.

          Reply
          • June 3, 2016 at 9:40 pm
            Permalink

            Awesome, thanks that works now!

            I have noticed that my classes from the Webservice which are marked with [DataContract] appear to have lost their methods. Is there a way to maintain that, so I can use the classes implemented by the webservice?

            Cheers!

          • June 3, 2016 at 10:41 pm
            Permalink

            (Marking methods with [OperationContract] doesn’t seem to work)

          • June 6, 2016 at 1:38 pm
            Permalink

            have you copied System.ServiceModel.dll in plugin folder of unity app and changed “API Compatibility Level” to .NET 2.0.

  • July 27, 2016 at 6:56 pm
    Permalink

    Very great tutorial! Thank you very much!

    I want to place this service on some free hosting: somee.com or smarterasp.net or so on. What must I write in App.config to do this?

    Reply
    • July 28, 2016 at 9:46 am
      Permalink

      I will suggest, leave the base address in wcf app.config file as the same – localhost:8080; but when you will call the service in unity the end point point address in the start function. There you should replace locahost to the address of the server where your service is running. Give it a try!

      Reply
      • July 29, 2016 at 2:53 pm
        Permalink

        The simplest way for remote hosting is using the “WCF Service” (“File” -> “New” -> “Web Site..” -> “WCF Service”)

        Reply
  • August 2, 2016 at 10:06 pm
    Permalink

    Great tutorial.

    Have you ever try to consume a WCF service in Duplex using Net.TCPBiding? I recieve the following error :

    NotSupportedException: Operation is not supported.
    System.ServiceModel.Channels.SecurityChannelFactory

    Reply
    • February 16, 2017 at 9:27 pm
      Permalink

      Once you will generate the proxy class then it will give you information about the class, their constructor and the methods that are exposed as the WCF service. Just like in the given demo “Service1Client” class and “getData” method is present in the proxy class. First create the instance of this class and then call the required WCF methods. Make sure you provide the correct endpoint address in the constructor.
      If the class is present in any namespace then import that namespace first with using statement.

      Reply
  • February 17, 2017 at 9:59 pm
    Permalink

    Hello Gyanendu Shekhar, thank you for your answer! I have the same problem.

    He have tried all the steps with 3 pages of webservices, respecting all the points, and in the unity when I play the same errors:

    WebException: There was an error on processing web request: Status code 500(InternalServerError): Internal Server Error
    System.ServiceModel.Channels.HttpRequestChannel+HttpChannelRequestAsyncResult.WaitEnd ()
    System.ServiceModel.Channels.HttpRequestChannel.EndRequest (IAsyncResult result)
    System.ServiceModel.Channels.HttpRequestChannel.Request (System.ServiceModel.Channels.Message message, TimeSpan timeout)
    System.ServiceModel.ClientRuntimeChannel.Request (System.ServiceModel.Channels.Message msg, TimeSpan timeout)
    System.ServiceModel.ClientRuntimeChannel.Request (System.ServiceModel.Description.OperationDescription od, System.Object[] parameters)
    System.ServiceModel.ClientRuntimeChannel.DoProcess (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters)
    System.ServiceModel.ClientRuntimeChannel.Process (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters)

    I show you my “callService.cs”:

    using UnityEngine;
    using System;
    using System.ServiceModel;

    public class callService : MonoBehaviour
    {

    void Start()
    {
    GlobalWeatherSoapClient client = new GlobalWeatherSoapClient(new BasicHttpBinding(), new EndpointAddress(“http://www.webservicex.net/globalweather.asmx?WSDL”));
    print(client.GetCitiesByCountry(“Spain”));
    }
    }

    Can you show me how I have to make this procces, but with remote address, you are with local service. I am trying with internet service. Is crazy, I make the same like you and I have error issues.
    Can you help me please?

    Thank you a lot!

    Reply
    • February 17, 2017 at 11:29 pm
      Permalink

      Hi Mikel, The service that you want to consume is ASP.Net Web Service (.asmx). This tutorial helps you to consume WCF Service only. I tried the service that you provided as ASP.Net Web service and it is working fine. I am able to call GetCitiesByCountry() method. Soon (probably in 1-2 days), I will provide tutorial on calling asmx services in unity3d.

      Reply
  • February 18, 2017 at 11:44 am
    Permalink

    Hello, this method doesn’t work on iOS.
    Use “wsdl” command instead “svcutil”

    Reply
  • March 2, 2017 at 5:42 pm
    Permalink

    Hello Gyanendu, If you can help me with this problem I thank you very much.

    Some company has sent me proxy script generated by them with svcutil.exe, but when I put that in project, jumps the following error:

    The type or namespace name Tasks' does not exist in the namespace System.Threading’. Are you missing an assembly reference?

    I can’t solve it, I need some library, but I don’t know where to import it.
    Do you know how I can solve this problem?

    Thank you!

    Reply
  • April 14, 2017 at 3:27 pm
    Permalink

    Hello Gyanendu:
    Would you mind tell me that why we have to copy the System.servicemodel.dll into Plugin folder? And why has to be in the folder “Plugin”?

    Reply
  • July 12, 2017 at 11:48 am
    Permalink

    Hello Gyanendu:
    i follow your tutorial, but use vs2010 to build the WCF service (with different class name), and Unity 5.6.0f3 to build the project.
    but when i run unity i cannot connect to wcf service, with these error:
    WebException: There was an error on processing web request: Status code 404(NotFound): NotFound
    System.ServiceModel.Channels.HttpRequestChannel+HttpChannelRequestAsyncResult.WaitEnd()

    Reply
    • July 12, 2017 at 10:25 pm
      Permalink

      Hi Joe. It seems unity client is not able to find WCF service. Make sure your WCF service is running and the endpoint address is correct in unity.

      Reply
  • October 28, 2017 at 6:19 am
    Permalink

    Hi will this work on android ios and webgl platforms? (with aot complation)

    Reply
  • November 7, 2017 at 3:05 pm
    Permalink

    Hi I have implemented all the things you have told here and it works really great, but I need to do something further than this with the classes described in WCF service. I have 3 classes in Unity, but I need to pass this class to WCF service. I made these classes to be available in Unity 3d inspector window so I can extend it within the inspector. My problem is as these classes are defined in Unity WCf service not recognizes it when I send it there. So I recreated same classes in WCF service and started an instance of the top class in a mono behavior script in Unity. Even though it seems like it has been created , I can not see the created instance in inspector window. I understand it is something about serialization just couldn’t figure out how to find a work around for it so that I can see the created instance of that class from WCF service in Unity inspector window.
    clasess are shown below.

    in WCF service
    ——————–
    namespace WcfPSVR
    {
    [DataContract]
    public class Score
    {
    [DataMember]
    public float TotalScore { get; set; }
    [DataMember]
    public StepScore[] Steps { get; set; }
    }
    }

    namespace WcfPSVR
    {
    [DataContract]
    public class StepScoreData
    {
    [DataMember]
    public string title { get; set; }
    [DataMember]
    public int stepNo { get; set; }
    [DataMember]
    public float stepScore { get; set; }
    [DataMember]
    public StepScoreItemData[] stepItems { get; set; }
    }
    }

    namespace WcfPSVR
    {
    [DataContract]
    public class StepScoreItemData
    {
    [DataMember]
    public string title { get; set; }
    [DataMember]
    public string tag { get; set; }
    [DataMember]
    public bool isPlanogram { get; set; }
    [DataMember]
    public int maxCount { get; set; }
    [DataMember]
    public float scoreWeight { get; set; }
    [DataMember]
    public float mslWeight { get; set; }
    [DataMember]
    public float goldWeight { get; set; }
    [DataMember]
    public float scoreValue { get; set; }
    [DataMember]
    public int scoreCount { get; set; }
    [DataMember]
    public float itemDataScore { get; set; }
    }
    }
    —————–
    and in Unity
    —————–
    using WcfPSVR;
    public class ScoreManager2 : MonoBehaviour
    {
    [SerializeField]
    public ScoreData allScoreData;
    }
    —————

    Thank you in advance of your reply .
    Regards

    Reply
  • April 28, 2018 at 6:52 pm
    Permalink

    i use this on my projects. its working perfectly. but when i request from server. its waiting till response come back. so unity using single thread i cant show any waiting, loading animation. how is it possible to change wcf servis working with callback. i will call method from unity client and i will show the procedure the callback will fire this procedure. unity will go on working and when callback fired i will do to do.

    how can i change the wcf web service this type ?

    Reply
  • May 24, 2018 at 5:46 pm
    Permalink

    Hi
    We simply used WCF(Windows Communication Foundation) in Previous versions(5) of Unity3D and when we exported our projects for android, it worked like a charm.

    But, recently we using new version of Unity (.Net 4.5), and when we using WCF in our project, we have a big problem. when we are debugging our project in windows its OK, but when we are exporting our project and try to running it on android system, it doesn’t work.

    any idea ?

    Reply
    • November 8, 2018 at 4:32 pm
      Permalink

      Hi mehrshad,
      I facing to the same problem; have you find any solution?
      I have tested to consume the WCF and Web services , both work perfectly in execution mode of Unity, but when I build the android application , the communication doesn’t work !

      Reply
  • June 14, 2018 at 7:32 pm
    Permalink

    Great tutorial. It works fine but I have a problem running it on WebGL. Somebody here said to use wsdl instead of svcutil but it still doesn’t work.

    Reply
  • August 12, 2018 at 2:20 pm
    Permalink

    Hello,
    I’ve tried your method and it worked perfectly in unity editor but its giving me error while building, “ArgumentException: The Assembly System.Data.Services.Client is referenced by System.Web.Extensions (‘Assets/Plugins/System.Web.Extensions.dll’). But the dll is not allowed to be included or could not be found.”

    I’ve tried changing the subnet and changing the .net to 4.6 but nothing worked.
    could you help me.

    Reply
    • August 12, 2018 at 2:47 pm
      Permalink

      Never mind i found the error, it was because the wrong System.Web.Extensions.dll was in the plugins folder to get the right one go to “C:\Program Files\{unity version you are using}\Editor\Data\Mono\lib\mono\2.0” and get the System.Web.Extensions.dll from there

      I’ll leave this comment if anyone faced the same problem.

      Reply
  • November 7, 2018 at 3:35 am
    Permalink

    Hy dude, thank you for your great tutorial, it helped me alot.
    I just have one problem for throwing FaultException from my service to my unity client. but my unity project cannot catch FaultException and just give me this message as an output: “There was an error on processing web request: Status code 500(InternalServerError): Internal Server Error”

    Could you please help me in this particular problem ,

    BR,

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *