For both my personal project as well as our group project Unity was chosen as the primary frontend.
Because of this It's important for us to know how to properly communicate with for example a Spring boot backend. For both project we will utilize REST calls for direct communication, however for my personal project I also need to use Websockets so that the backend can notify the frontend for changes.
REST calls are natively supported by C# and Unity so those were easier to implement, however after some research and looking around it became clear that websockets are not natively supported and require a library.
A rest controller handles HTTP requests if told to do so will send a reply back to where it got called from. To make a webrequest from unity I have used the built in UnityWebRequest. A UnityWebRequest is created within a coroutine, this allows Unity to run it next to the main thread. This is important because Unity is not that good with multithreading by default. If you were to run this method in the main thread it would lock it, freeze up the game and wait until it gets a response from the web server.
A callback is provided to pass back the return value from the web server.
The image below shows a rest controller. For more information how to set one up see the full document.
Implementation in Unity.
A websocket can send a message on a specified topic to all clients subscribed to that topic. This allows a web server to send a message to a client without the client ever asking for anything. This is useful for updating a client's state when something changed in the backend. I want to use this in my own application to notify the client when an item gets added to a users inventory.
To make this work in Unity the client establishes a connection to the websocket endpoint. From there the client can subscribe on a topic, in my personal application this will be their own username. When the server sends a message to the topic /topic/<players username> the players client will receive the message which can then be displayed on screen.
Websocket endpoint in spring boot.
Websocket implementation in Unity.
What did you learn and what will you do differently next time?
I now know how to properly work with websockets and unity webrequest.
After eventually figuring out how to make Unity play nice with websockets it was not very hard to work with. I have set up the websocket client class to be versatile so it can be dropped in any existing project with relative ease. Only a few things have to be edited/configured for it to work in any project, the same goes for my Rest implementation. I don’t think I would change much for the future, I am quite content with what I achieved and it does the job perfectly.