Create a server for your Unity game using .NET Core

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

How does this compare to something like photon? I know photon has limits and fees.

👍︎︎ 5 👤︎︎ u/[deleted] 📅︎︎ Mar 26 2022 🗫︎ replies

Been waiting for this ! Thanks!

👍︎︎ 2 👤︎︎ u/Khizar19993 📅︎︎ Mar 26 2022 🗫︎ replies

This post appears to be a direct link to a video.

As a reminder, please note that posting footage of a game in a standalone thread to request feedback or show off your work is against the rules of /r/gamedev. That content would be more appropriate as a comment in the next Screenshot Saturday (or a more fitting weekly thread), where you'll have the opportunity to share 2-way feedback with others.

/r/gamedev puts an emphasis on knowledge sharing. If you want to make a standalone post about your game, make sure it's informative and geared specifically towards other developers.

Please check out the following resources for more information:

Weekly Threads 101: Making Good Use of /r/gamedev

Posting about your projects on /r/gamedev (Guide)

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

👍︎︎ 1 👤︎︎ u/AutoModerator 📅︎︎ Mar 26 2022 🗫︎ replies

This is excellent! This is a quick explanation of important technology, where I found it hard to find good game (Unity) oriented information. I'm looking forward to the next part - subscribed! Are you also going to show how to host the server (cheaply) on Azure or AWS? With https?

👍︎︎ 1 👤︎︎ u/paul_sb76 📅︎︎ Mar 27 2022 🗫︎ replies
Captions
hello and welcome today i will be showing you how to make a custom asp core back end for your game it would be safe to say that my balls are tingling i'm combining two of my favorite things servers and games and uh i just hope you enjoy so in the first episode i'm going to be showing you how to scaffold the projects how to share models between both your server and your unity project i'm going to show you what the hell an asp core application actually is what an api is how it works i'll show you how to get data from your game to the server and server to the game in part two i'll be adding authentication and authorization as well as hooking it up to a database so if that's all you really need to see head across to part two if it's out uh but yeah let's just get stuck in so what you want to do is if you're starting fresh which is how i'm going to do it here uh create your main root folder okay i'm going to be calling this project game server alright so let's create the application i'm using the writer ide uh you may be using visual studio that's perfectly fine everything is accomplished in roughly the same way it's just the windows might look differently but the projects themselves exactly the same so in writer i'm just going to get a new solution i'm going to call this game server and this is the folder my root folder here so i'm just going to put it there i'm not going to create a directory for the solution and create and that will just give us this very bare solution basically it's just a solution file with no projects whatsoever i'm not going to go over both steps in both ides every time but just to show you how similar it is in visual studio just go create a new project you'd go blank solution like that then you'd pick your solution name and away you go so everything is roughly the same you just access it in different ways depending on the idea all right there is way too much in this tutorial to explain everything so if i brush over something that's up to you to go and google otherwise this is going to be a 25 piece tutorial which i do not want that to be so uh to begin let's create a new project inside of the solution so i'm going to go add new project and this first one will be an asp.net core web application make sure you're using core because that means it's cross-platform it can be used on windows linux and mac uh make sure you don't use this which is the old.net standard uh sorry the net framework version which is just for windows so netcore you'll be able to select a type whether it's here or in visual studio i'm going to be doing a web api this is just like the initial scaffold of the application it'll just give you some sample code to show you like roughly how to do it uh c sharp authentication no authentication we'll do that ourself and let's just call this server and it's going to go in the root folder there and press create next we need to share data between unity and the server right so a newbie way to do that would be to duplicate the models right put it on server and unity which by the way is what a lot of people do when working with say a c-sharp back-end and a javascript front-end they'll duplicate the models which is hella messy and hugely error-prone so anyway to alleviate that what we'll do is we will create a new project and this will be a class library and i'm just going to call this shared library i would have normally called it library but unity themselves have the library folder right so that will clash so shared library and create so all that is is when you build it it's just a binary and it's just got all these classes in it so our first class for example let's just rename that right now to something like player and let's make a few properties so uh maybe a level and maybe a float here and that can be health we've got this library here and it's got a player and that's all it's got so what is an api and specifically what is an asp core api it is what we call a restful service so basically we open up all these endpoints and while no one's hitting it it's just sitting there idle right as soon as someone hits it it'll run some logic and it will return data or it will post some data put some data in a database whatever it's just receiving requests and sending responses okay simple as that and what actually sucks is their sample controller is just like super verbose it doesn't need to be this complex and scary looking so let's actually delete this weather forecast controller and weather forecast let's just delete those and let's make our own which will be much simpler player controller now controller is not only convention but required in this framework for it to be picked up and auto mapped and we will inherit from controller base controller base is what allows us to actually make this a controller and provides us with a whole bunch of controller functionality we need a few other things the first one will be api controller and lastly is the routes it allows us to not have to do any kind of manual mappings for our controllers for them to actually be active they'll just automatically be there for us so you just put in some brackets and write controller which is the convention that we're using here okay so now we have our controller set up and a good way to think about the controller is just a group of endpoints and then inside of this controller we actually write our endpoints so for example we'll write one now where we will return a player aha so we don't actually have access to this player right now because it's in the shared library so there's a few ways to add a reference to this project into this project if you're using writer or resharper for visual studio it should just be able to find it automatically although who knows maybe the new version of visual studio can also do that if that doesn't work right click on your server add add reference and just click your shared library here so now this project has this as a dependency and here we'll just include the missing reference and then sorry this function is going to return a player and let's just call it get and then in here let's just make a new player like that and then down here we will return that player uh easy as pie uh another thing that you need to do and this is the last bit of boilerplate i promise uh just say that this is in fact a get request as opposed to like a post or a patch or a put so a get request is just a endpoint that you can call with no payload and you can get some uh data back all right so that's actually all you need to set up your first get request so let's just run it and you'll see this swagger interface and swagger is just a api docs auto-generated plug-in kind of thing and it just allows you to see all your endpoints uh i actually usually turn it off which i'll show you how to do later yep my application has found my uh player endpoint my player controller because we've used the correct convention and decorate it with these attributes and we can actually try it out let's execute it and it has responded with our player cool banes alright next what if we would like to actually post data to our server so that is accomplished just as easy let's do a http post public and let's actually return a player still so like maybe they created the player and when we actually return the player back to them it's got a an actual id that has been assigned by the database so let's say post and this will accept a player object and then in here we'll just say uh player has been added to the database and then let's just assume the player has been added to the database it was probably given an id a unique id so we'll actually return the player cool so now if we press run we'll see now we have two endpoints one get and one post so if we go to the post here we can try out the end point and let's just say level uh seven this is ridiculous because it's not actually going to do anything uh but yeah it's returning it's returning our model that we just sent so we've got a post and a get but what if you need a little bit more control over what you're querying uh what if you would like a player with an id of 100 say and actually we don't have an id on here so let's just add an id inch id so there's a few ways to send data through uh we can do it via query strings so let's do it like that from query this will be int id and then here let's just uh trick it and say the id is the id that we asked let's just pretend that we got it from the database so if we try that and this is from query so let's go to our player endpoint and then with query strings you put a question mark and you say id for example because that's what we are calling our property and let's just say is equal to 100. so as you can see it is passing through that level of 100 there so that's one way to do it with query strings and by the way if you needed more query strings let's say um string name for example you would do it like this so you only have a question mark for the first one after the second one you now need a ampersand and you'll put name like that okay next is to do it via route so this is probably the better way to do it when you're just doing a simple query like this so you can do like this and you can do id and we'll change this from query to from route so now when we press play we get it like this we go player forward slash and then uh 150. so that's doing it via route so depending on what you want to do especially if it's a website you've you've always got different options for different uh context okay so let's actually talk about how this program is constructed so here we've got this program file now this actually in net five and below used to be two files startup and program and they have combined them and also removed a heap of boilerplate so now we've just got this nice top level block of code much nicer to work with so let's do a few things and simplify this for one i don't want swagger anymore that api construction thing so i'm going to remove these two things swagger and api explorer and i'm also going to remove these and i'm also actually going to remove the nougat package so depending on if you're in writer or visual studio just right click your actual server application and go manage nougat packages um as you can see i've got the swashbuckle here i'm going to remove that just to make it all clean and also one more bit of cleanup from that is uh you know when you press start on the application it actually automatically goes to the that swagger documentation that's because we need to change our launch settings so this is set to swagger the launch earl i'm just going to set that to player i know this is very rapid fire but uh you pause if you need to keep up so this class is split into two separate parts although it kind of doesn't really look like it first is the dependency injection part so if you don't know what dependency injection is it is the concept of supplying a pre-built class to other classes and objects so that these other classes and objects don't have to build it themselves now this provides a whole bunch of benefits one of the major ones is how easy it is to test actually let me just show you a really quick uh example so let's create a folder here and i'm going to call this services and in services i'm going to make a new file and i'm going to call this player service goalie golly player service make that a bit bigger in here i'm going to have a function that is going to return void and it's going to be called do something and it's just going to write a line that says hey uh so but just pretend that this is doing a whole bunch of stuff like uh actually grabbing the players from the database uh querying the players uh listing players changing players whatever for now we're just gonna have a do something and now say that we want this uh player service all over the place right uh sure we could construct it every time we need it or we could use dependency injection so let's go to program and let's say builder services and i'm going to add a scoped version so basically what scoped means is every single time the controller is accessed it's going to create whatever whatever i'm trying to give it brand new all right and this will be the player service just like that and now in my player controller i can just create a constructor and inside my constructor i can request for the player service player service and then i'll create a field here equals player service so now in my get request i can do player service dot do something and if we run the application and hit up player and that is actually with a route isn't it and then we go over here and we'll see that hey has actually been written to the console so yeah super easy to use dependency injection and makes it very very nice to test as i said it makes it nice and easy to test and i'll show you actually how to do that because it's a it's a vital lesson so let's create an interface instead and let's call this i player service and this is going to have that function signature and then this is going to inherit from i sorry implement uh iplayer service and then let's also have another one here which is called mock uh player service so hey from the mark service so now in our program we can say we can change this to iplayer service so we know that this service that we're injecting is of type iplayer service and then we can give it a the concrete class so for now let's say we want to use the mock player service because i want to test this and let's just say this main service is actually making database calls and it's actually affecting the database but of course i don't want to do that on a production database right i just want to test that all my logic is working so now i just go to program and i send in my mock class do all my tests and then for production we change it back and just remove the mark right that's an easy way to test your services super super easy um all right and of course because we're actually injecting iplayer service we actually have to uh accept iplayer service here not service or that would have thrown a error all right so that's the dependency injection part the next part here is the pipeline or adding your middlewares so basically this code will run every single time uh one of these endpoints are hit okay so for this first one for example once you've got your server in production if someone tries to go to your endpoint here but with http this will automatically redirect them and they'll use the https version this one offers authorization which i'm going to get into in the uh next video and then this one maps the controllers so it's actually looking for the convention of player controller and then it maps it as a player controller another thing because we removed swagger we actually have no easy way to test this post right because of course we can do a get but you can't add a payload in uh in a browser like this so what i use to test my uh post request is postman and i'll just show you how this works so with player we can just do player and 500 level 500 player and you'll see that it has made the get request uh and then i also was going to show you the post so let's actually copy this and let's just uh post it right back so i'm going to add a body to this raw it's going to be jason send and as you can see we have now uh tested the get and the post everything works okay so i feel like i'm covering a trillion topics all which need their own tutorial but uh sorry about that but not sorry last thing we need to do is communicate between our server and our game so it would be nice if we could simply add a reference like we did here right we added a reference to our shared library from our server but it's not that easy with unity it's a little bit more fiddly so and actually we haven't even created our game yet so let's go to unity hub new projects um i'm going to put it in the root of my game server project folder and i'm just going to call my game game very imaginative all right so once your game has been created go ahead and just create a scripts folder and create your first script i'm just going to call this the game manager so without without a script the actual uh solution for this game doesn't get created so just create that first and i'm just going gonna open that up okay so there is the option to add our game to this solution here and kind of keep it all in one ide but i strongly suggest against it because a lot of the time you're going to be debugging the server and you're wanting to be debugging the game at the same time and it just it's really clumsy so i keep them as separate solutions but you can add it here just in the same way that you added the shared library uh just know that i suggest against it so what we want to do is when this shared library has changed for it to build and then copy the dll into our unity project that's how they can that's how unity can use the code so let's create a folder i'm going to call this dlls uh that looks weird like that dlls that's better and obviously we don't want to do that manually so we can create a little script so right click on your shared library go to edit and then edit the shared library cs proj that'll just be slightly different uh if you're using visual studio but this will be the same in here let's do a post build event now i'm on windows so i'm going to be using copy but you might be on linux so you might have to do something slightly different i'm going to copy the shared library dll and use a special little argument here called out der and then here what we need to do is go back a whole bunch of folders uh and then put it into our game folder it's a it's a little bit messy if somebody knows a better way to do this please tell me in the comments but effectively what we're going to be doing is this back a few and then we'll be going into our game folder and then into our assets folder and then into our dlls folder and then finally we're going to be calling it shared library.dll and i betcha that's wrong but uh we can check that easily by just going build and you'll see that it has indeed copied and if we are just amazing it'll already be oh first run cool so that's what you want to do obviously you'll need to change this depending on how you set up your project and as code has changed on unity now we actually need to go inside unity so it can compile and you'll see we've got our shared library here and you don't actually need to change anything here in our game manager let's actually see if we can access the uh classes new player there we go in our shared library so it's added the shared library namespace let's get rid of those puppies excellent so now we have models that are being shared across two projects which makes it super duper easy now that is one massive advantage over using a node server for any c-sharp client you can share your models all right so next is to actually call the api and get the actual data so i have created this little http client that uses uh the unity web request unity web request in my opinion is disgusting and i hate how it has to be in a co-routine it makes it hard to use hard to return data so i did this kind of like little uh work around so that i've got an asynchronous workflow here uh i'll include this on my patreon as well as this whole project so you can just download this whole project and fire it up and you'll have a game and a server uh built for you all right so before we do this let's actually make sure that our server is running so let's run it and let's copy the endpoint here and then in our game let's do var player equals and i'm going to use my http client here and get and this is going to be of type player then in here we're going to use that and then say level 500 and this is an asynchronous function so i'm going to make that a weights and async here um and then let's set a little breakpoint and press debug start a debug session and over here i'm just going to attach my game manager to this any script and press play and what have we got here we have got none aha one last thing to make this work is that the unity jason utility is garbage and it's super temperamental and you need to hold its hand every step of the way there are two problems one the unity json utility cannot deserialize properties so it has to be fields so let's make those fields and the thing that sucks is that the default json serializer for net core uh which is system.txt.json doesn't it actually ignores fields it only looks for properties now what we could do is add a json uh include here but this actually now includes this namespace in our library which will also make unity its pants so we're not gonna do it that way we're just going to change the default uh serializer for our server so in program where we've got add controllers here this is where we change our default serializer i know this is probably word spaghetti to you but just bear with me and we'll add a new nougat package here and this will be uh the aspcor.mvc.newtonsoft by the way if you haven't heard of newtonsoft it is actually the most popular library the most downloaded library ever in the whole c sharp ecosystem so make sure you're using the correct version that you're using i'm using uh donna 6. so i'm just going to install that in my project and it's in now here i can just say add newton's soft jason so that will now allow us to serve the fields now the second of two problems is that for unity json serializer to actually deserialize something the name casing has to be uh spot on so uh this server by default returns camel case because that is the standard for front-end uh javascript but we actually need it to return pascal case so it matches our model exactly and that's very easy to add we'll just add some options here and in here we'll say serializer settings and set the contract contract resolver equals to a new default contract resolver i know that's a bit weird but this will allow us to return pascal case and actually i didn't even demonstrate that did i so i'm just going to remove that i'm going to run it and let's actually ping the endpoint so you'll see here that it's returning a camel case and now if we remove it you're about to have your minds blown it indeed returns a passport case now so now that we have fondled uh unity's json serializers bowls we can finally actually use it and it will accept uh what we're sending it um so let's run the server let's go across to our game yeah that all looks good we've got a breakpoint let's start debugging let's press play and it should hit our breakpoint over here and let's see have we grabbed our player yes we have and actually you know what i should be showing you is that the endpoint is actually hit on the server so uh let's go to our server and then in the player controller let's set a breakpoint here in our get request and we'll debug it instead of just running it and then let's play our game so that we can make the request and as you can see the endpoint has been hit with id 500 and we'll come down here and we'll do our player service and we'll say hey uh somewhere in our console hey so now we've set up all our projects we're sharing the models between them we're doing all this fiddly stuff to make it work with unity uh we're posting and we're getting so in the next video i'm gonna be setting up authentication and authorization as well as uh hooking up a little database so stay tuned for that subscribe like the video and i hope you learned something and i hope this was actually fun and i'll see you next time bye
Info
Channel: Tarodev
Views: 57,500
Rating: undefined out of 5
Keywords: unity server, unity backend, unity asp core, asp core server, unity server client, saving player data, custom server, custom server unity, c# server, C# unity server, .net server, .net unity server, create a server, game server, game development, unity multiplayer, dependency injection
Id: jLy7A702GhA
Channel Id: undefined
Length: 24min 51sec (1491 seconds)
Published: Sat Mar 26 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.