Unity 5.0 introduced WebGL support for games built with Unity. Let’s see how we can use Web Sockets to build a real time multiplayer game with Unity. With the Web Socket support, we built a Pong game for our digital signage screens where two users can join the game and play against each other using their mobile phones as gamepads controlling the movement of their pad on the big screen.
Handling sockets on Unity Game
The first step we need is to connect to a Web Socket server:
Once we are connected to the server, we can receive messages on the socket using
RecvString and send messages using
SendString. The sample plugin doesn’t support events for messages, errors etc. To check for new messages available through the socket, use
RecvString method in
Handling sockets on GamePads
The game that we are developing allows users to join the game through their mobile phones by navigating to a webpage. Let’s see how we can handle the sockets on the gamepad. As before, we first need to connect to the Web Socket server.
The last step is to send the position of the pad to the game whenever it is moved.
Putting it all together
On a 3G network, we have less than 100ms ping roundtrip which allows for almost unnoticeable delay between user input on a mobile phone and the actual game displaying on another screen.