How can I send data to a Unity3D game through SignalR in HTML5?

I followed a tutorial from a German blog here .

Subsequently, I created a script that sends the imprinted HTML5 hand coordinates when clicked on the screen. I would like to send these coordinates to Unity Game using the provided server and clients.

Until I move forward with this specific example, I will look at other SignalR examples and accept other Networking offers that will allow Unity and the web player to have a connection.

Unity code: (sends data) Playercontrollers.cs (1/2)

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<SignalRUnityController>(); var corner = new Vector3(Screen.width, Screen.height, 0f); var targetWidth = cam.ScreenToWorldPoint(corner); float playerWidth = GetComponent<Renderer>().bounds.extents.x; float playerHeight = GetComponent<Renderer>().bounds.extents.y; maxWidth = targetWidth.x - playerWidth; maxHeight = targetWidth.y - playerHeight; standardSprite = this.GetComponent<SpriteRenderer>().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<Rigidbody2D>().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<SpriteRenderer>().sprite = clickedSprite; } private void MouseUp() { Debug.Log("MouseUp"); this.GetComponent<SpriteRenderer>().sprite = standardSprite; } public static void Receive() { Debug.Log("Change position from controller"); //var newPosition = new Vector3(450, 175, 0f); //GetComponent<Rigidbody2D>().MovePosition(newPosition); } } 

SignalRUnityController.cs (2/2)

 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 => { Debug.Log("signalR called us back"); Playercontrollers.Receive(); }; _hubConnection.Start(); } else Debug.Log("SignalR already connected..."); } /// <summary> /// Send single message of direction over broadcast /// </summary> // 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"); } } 

Visual Studio Project, (Index and Hubs)

 <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title> Unity to webPlayer Sample </title> <Style> 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; } </Style> </head> <body> <div id="contentContainer"> <img id="player" src="images/OpenHand.png" /> </div> <div id="infoContainer"> <label id="message"></label> </div> <div id="transportContainer"> <label id="connected"></label> </div> <!---Script references. --> <!--Reference the jQuery Library54321. --> <script src="Scripts/jquery-1.6.4.min.js"></script> <!--Reference the SignalR library54321. --> <script src="Scripts/jquery.signalR-2.1.1.min.js"></script> <!--Reference the autogenerated SignalR hub script. --> <script src="signalr/hubs"></script> <!--Add script to update the page and receive messages.--> <script src="//www.kirupa.com/prefixfree.min.js"></script> <script type="text/javascript"> 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 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(); }); }); }); </script> </body> </html> 

SIgnalRHub (2/3)

 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 { /// <summary name="SignalRHub">Name of the c# file</summary> [HubName("hub") ] public class signalRHub : Hub { /// <summary> /// The purpose of receive if for the Unity to have a function called receive that receives data from the web page /// </summary> /// <param name="name">name of the connection</param> /// <param name="message">single message to be sent through network</param> public void Send(string name, string message) { //Call the broadcastMessage method to update the clients. Clients.All.broadcastMessage(name, message); } } } 

Startup.cs

 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(); } } } 

Now part of the solution:

  • Do I need to add another signalHub?
  • Should I change? Still use streaming for everyone?
  • Which file can I change for UNity? Should I create another .cs file called Listener.cs?
  • Which file can I change for the HTML5 index?
  • What is the function called (receive?)
  • Will the solution scale or is it a patch?
+5
source share

All Articles