title: How can I send data to a Unity3D game through SignalR on HTML5?
body: <p>I followed the tutorial from the German Blog <a href="http://www.microsofttranslator.com/bv.aspx?from=&amp;to=en&amp;a=http%3A%2F%2Fcodefest.at%2Fpost%2F2014%2F09%2F11%2FSignalR-und-Unity-in-euren-Multiplayer-Indie-Games.aspx" rel="nofollow noreferrer">here</a>.</p>
  
  <p>Afterwards I created a script that sends prints out the coordinates of the HTML5 hand when clicked on the screen. I would like to send those coordinates to the Unity Game using the provided Server and Clients.</p>
  
  <p>While I am not moving forward with this particular example, I will be looking at other examples with SignalR, and will take other Networking suggestions that will allow unity and webplayer to have connection.</p>
  
  <p><strong>Unity Code: (sends data) 
  Playercontrollers.cs(1/2)</strong></p>
  
  <pre><code>using UnityEngine; 
  
  public class Playercontrollers : MonoBehaviour { 
  
      public Camera cam; 
      private float maxWidth; 
      private float maxHeight; 
  
      bool isHandOpen = true; 
      public Sprite clickedSprite; 
      private Sprite standardSprite; 
  
      private SignalRUnityController _signalr; 
  
      void Start() 
      { 
          if (cam == null) 
              cam = Camera.main;
  
         _signalr = GameObject.Find("SignalRObject").GetComponent&lt;SignalRUnityController&gt;();
  
          var corner = new Vector3(Screen.width, Screen.height, 0f); 
          var targetWidth = cam.ScreenToWorldPoint(corner); 
          float playerWidth = GetComponent&lt;Renderer&gt;().bounds.extents.x; 
          float playerHeight = GetComponent&lt;Renderer&gt;().bounds.extents.y; 
          maxWidth = targetWidth.x - playerWidth; 
          maxHeight = targetWidth.y - playerHeight; 
  
          standardSprite = this.GetComponent&lt;SpriteRenderer&gt;().sprite; 
  
      } 
      void FixedUpdate() 
      { 
          var currentPosition = cam.ScreenToWorldPoint(Input.mousePosition); 
          float targetWidth = Mathf.Clamp(currentPosition.x, -maxWidth, maxWidth); 
          float targetHeight = Mathf.Clamp(currentPosition.y, -maxHeight, maxHeight); 
          var newPosition = new Vector3(targetWidth, targetHeight, 0f); 
          GetComponent&lt;Rigidbody2D&gt;().MovePosition(newPosition); 
  
          if (Input.GetMouseButtonDown(0)) 
          { 
              isHandOpen = false; 
              MouseDown(); 
          } 
          else if(Input.GetMouseButtonUp(0)) 
          { 
              isHandOpen = true; 
              MouseUp(); 
          } 
  
          var worldCoordinates = cam.WorldToScreenPoint(newPosition);
          var json = "{"+string.Format("\"x\": \"{0}\", \"y\": \"{1}\", \"handOpen\": \"{2}\"", worldCoordinates.x, worldCoordinates.y, isHandOpen) +"}";
          //var json = "{\"x:791, y:10,handOpen: True\"}";
          Debug.Log(json);
          _signalr.Send("Position", json); 
  
      } 
  
      private void MouseDown() 
      { 
          Debug.Log("MouseDown"); 
          this.GetComponent&lt;SpriteRenderer&gt;().sprite = clickedSprite; 
  
      } 
  
      private void MouseUp() 
      { 
          Debug.Log("MouseUp"); 
          this.GetComponent&lt;SpriteRenderer&gt;().sprite = standardSprite; 
      } 
      public static void Receive()
      {
          Debug.Log("Change position from controller");
          //var newPosition = new Vector3(450, 175, 0f);
          //GetComponent&lt;Rigidbody2D&gt;().MovePosition(newPosition);
  
      }
  
  } 
  </code></pre>
  
  <p><strong>SignalRUnityController.cs</strong> (2/2)</p>
  
  <pre><code>using SignalR.Client._20.Hubs;
  using UnityEngine;
  using System.Collections;
  
  public class SignalRUnityController : MonoBehaviour {
  
      public bool useSignalR = true;
      public string signalRUrl = "http://localhost:50283/";
  
      private HubConnection _hubConnection = null;
      private IHubProxy _hubProxy;
      private IHubProxy _hubProxyReceive;
      private Subscription _subscription;
      public Playercontrollers player;
  
  
  
      //start connection to the outer web page
      void Start () {
  
          if (useSignalR)
              StartSignalR();
      }
  
      void StartSignalR()
      {
          if (_hubConnection == null)
          {
              _hubConnection = new HubConnection(signalRUrl);
  
              _hubProxy = _hubConnection.CreateProxy("signalRHub");
              _subscription = _hubProxy.Subscribe("broadcastMessage");
              _subscription.Data += AudioDataLoadState =&gt;
              {
                  Debug.Log("signalR called us back");
                  Playercontrollers.Receive();
  
              };
              _hubConnection.Start();
  
          }
          else
              Debug.Log("SignalR already connected...");
      }
  
  
      /// &lt;summary&gt;
      /// Send single message of direction over broadcast
      /// &lt;/summary&gt;
      // Update is called once per frame
      public void Send(string method, string message){
          if (!useSignalR)
              return;
  
          var json = "{" + string.Format("\"action\": \"{0}\", \"value\": {1}", method, message) + "}";
          _hubProxy.Invoke("Send", "UnityClient", json);
  
      }
      public void Receive(string method, string message)
      {
         // if (!useSignalR)
            //  return;
  
          //_hubProxyReceive.Subscribe("Receive", "UnityClient");
  
      }
  
  }
  </code></pre>
  
  <p><strong>Visual Studio Project, (index and hubs)</strong></p>
  
  <pre><code>&lt;!DOCTYPE html&gt;
  
  &lt;html lang="en" xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;head&gt;
      &lt;meta charset="utf-8" /&gt;
      &lt;title&gt; Unity to webPlayer Sample &lt;/title&gt;
  
      &lt;Style&gt; 
        body {
          background: url(images/game-background.png);
          /*background-size54321:*/
          background-repeat: no-repeat;
        }
  
        #player {
  
          position: absolute;
  
          top: 30px;
  
          left: 30px;
  
        }
        #contentContainer {
      width: 500px;
      height: 500px;
      border: 5px black solid;
      overflow: hidden;
      background-color: none;
      cursor: pointer;
  }
  
        &lt;/Style&gt;
  
  &lt;/head&gt;
  
  
  &lt;body&gt;
      &lt;div id="contentContainer"&gt;
          &lt;img id="player" src="images/OpenHand.png" /&gt;
          &lt;/div&gt;
  
  
          &lt;div id="infoContainer"&gt;
  
              &lt;label id="message"&gt;&lt;/label&gt;
  
          &lt;/div&gt;       
          &lt;div id="transportContainer"&gt;
  
              &lt;label id="connected"&gt;&lt;/label&gt;
  
          &lt;/div&gt;
  
          &lt;!---Script references. --&gt;
          &lt;!--Reference the jQuery Library54321. --&gt;
  
          &lt;script src="Scripts/jquery-1.6.4.min.js"&gt;&lt;/script&gt;
  
          &lt;!--Reference the SignalR library54321. --&gt;
  
          &lt;script src="Scripts/jquery.signalR-2.1.1.min.js"&gt;&lt;/script&gt;
  
          &lt;!--Reference the autogenerated SignalR hub script. --&gt;
  
          &lt;script src="signalr/hubs"&gt;&lt;/script&gt;
  
          &lt;!--Add script to update the page and receive messages.--&gt;
      &lt;script src="//www.kirupa.com/prefixfree.min.js"&gt;&lt;/script&gt;
          &lt;script type="text/javascript"&gt;
              var theThing = document.querySelector("#player");
              var container = document.querySelector("#contentContainer");
  
              container.addEventListener("click", getClickPosition, false);
  
              function getClickPosition(e) {
                  var parentPosition = getPosition(e.currentTarget);
                  var xPosition = e.clientX - parentPosition.x - (theThing.clientWidth / 2);
                  var yPosition = e.clientY - parentPosition.y - (theThing.clientHeight / 2);
  
                  theThing.style.left = xPosition + "px";
                  theThing.style.top = yPosition + "px";
                  console.log(xPosition + " " + yPosition);
              }
  
              // Helper function to get an element's exact position
              function getPosition(el) {
                  var xPos = 0;
                  var yPos = 0;
  
                  while (el) {
                      if (el.tagName == "BODY") {
                          // deal with browser quirks with body/window/document and page scroll
                          var xScroll = el.scrollLeft || document.documentElement.scrollLeft;
                          var yScroll = el.scrollTop || document.documentElement.scrollTop;
  
                          xPos += (el.offsetLeft - xScroll + el.clientLeft);
                          yPos += (el.offsetTop - yScroll + el.clientTop);
                      } else {
                          // for all other non-BODY elements
                          xPos += (el.offsetLeft - el.scrollLeft + el.clientLeft);
                          yPos += (el.offsetTop - el.scrollTop + el.clientTop);
                      }
  
                      el = el.offsetParent;
                  }
                  return {
                      x: xPos,
                      y: yPos
                  };
              }
              $(function () {
                  var hub = $.connection.SignalRHub;
                  var echo = $.connection.echo;
  
                  echo.client.greetings = function (message) {
                      $('#message').html(message);
  
                  };
  
                  var started = hub.start();
  
                  started.done(function () {
                      echo.server.say("hello! New User 5671 joined");
                  });
  
              });
  
              $(function () {
                  //$('#message').text('connected');
  
                  //  Declare a proxy to reference the hub.
  
                  var signalrHub = $.connection.signalRHub;
  
  
  
  
  
                  //Create a function that the hub can call to broadcast messages.
  
                  signalrHub.client.broadcastMessage = function (name, message) {
                      console.log(message);
                      var messageobj = JSON.parse(message);
  
  
  
                      if (messageobj.action == 'Position') {
                          console.log("Position + Position");
  
                          $('#player').css('left', messageobj.value.x + 'px');// update the x value
                          $('#player').css('top', 500 - $('#message').height() - messageobj.value.y + 'px');// update the x value
                          $('#message').text('x:' + messageobj.value.x + "px, y:" + messageobj.value.y + 'px');
                          if (messageobj.value.handOpen == 'True')
                              $('#player').attr('src', 'Images/OpenHand.png');
                          else
                              $('#player').attr('src', 'Images/ClosedHand.png');
                      }
                  };
  
                  var started = signalrHub.start({
                      transport: [
                      'webSockets',
                      'longPolling',
                      'serverSentEvents',
                      'foreverFrame'
                      ]
  
                  });
  
                  //start the connection to the server to display on the webpage
                  $.connection.hub.start().done(function () {
                      $('#message').text('connected');
                      $('#connected').text('connected, transport: ' + signalrHub.transport.name);
                      console.log('connected, transport: ' + signalrHub.transport.name)
                  });
  
  
                  $.connection.hub.start().done(function () {
                      $('#contentContainer').click(function () {
                          console.log("Clicked");
                          //Call the Send method on the hub. 
                          //chat.server.send($('#displayname').val(), $('#message').val());
                          // Clear text box and reset focus for next comment. 
                          //$('#message').val('').focus();
                      });
                  });
  
              });
  
          &lt;/script&gt;
  
  
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p><strong>SIgnalRHub(2/3)</strong></p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using Microsoft.AspNet.SignalR;
  using Microsoft.AspNet.SignalR.Hubs;            //include this to add hub names ["echo"]
  
  namespace SignalRUnityWeb
  
  {
      /// &lt;summary name="SignalRHub"&gt;Name of the c# file&lt;/summary&gt;
      [HubName("hub") ]
      public class signalRHub : Hub
      {
          /// &lt;summary&gt;
          /// The purpose of receive if for the Unity to have a function called receive that receives data from the web page
          /// &lt;/summary&gt;    
          /// &lt;param name="name"&gt;name of the connection&lt;/param&gt;
          /// &lt;param name="message"&gt;single message to be sent through network&lt;/param&gt;
          public void Send(string name, string message)
          {
              //Call the broadcastMessage method to update the clients.
  
              Clients.All.broadcastMessage(name, message);
          }
      }
  }
  </code></pre>
  
  <p><strong>Startup.cs</strong></p>
  
  <pre><code>using System;
  using System.Threading.Tasks;
  using Microsoft.Owin;
  using Owin;
  
  [assembly: OwinStartup(typeof(SignalRUnityWeb.Startup))]
  
  namespace SignalRUnityWeb
  {
      public class Startup
      {
          public void Configuration(IAppBuilder app)
          {
              // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
              app.MapSignalR();
          }
      }
  }
  </code></pre>
  
  <p>Now the solution part:</p>
  
  <ol>
  <li>Do I have to add another signalHub?</li>
  <li>Should I change Still use broadcast to all?</li>
  <li>Which file do I change for UNity? Should I create another .cs file called Listener.cs?</li>
  <li>Which file do I change for the HTML5 index to be correct?</li>
  <li>What is the name of the function(receive?)</li>
  <li>Will the solution scale or is it a patch?</li>
  </ol>