Unity3d - UnityWebRequest Get async tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys carlos here while making games with unity you will find the need to send and request data from a remote server one of the most common ways is by using a restful api and this is nothing else that code that allows two software programs to communicate with each other with rifle we can get put post and delete data types to communicate your game and the server will need to use a common language that's json json is a lightweight format for storing and transporting data it's also self-describing and easy to understand for all this there is an api available in unity that's the unity web request so let's try to use it the first step will be to get a json from any web server for this video i will be using a free public api website feel free to use your own and just replace the url in the following example as long as you get a json response you are good to go let's open the unity editor and create a script to write our first get request the name of the class is irrelevant i will call mine testcontroller remove any unused assemblies from our class you can do this by clicking on the light bulb and selecting the option remove unnecessary using or with the shortcut ctrl rg and create a method called test get again the name could be anything now we declare a url variable and assign an empty string for now we will inject later the actual url of the web api of our choice here's a tip declare variables by using the var data type the compiler will resolve the type when a value is assigned in this case an empty string will make this a variable of type string next we will use the unity web request api for the first time as you can see the compiler will not recognize unity web requests until we add the respective assembly at the top of the class to do that we can use the libel menu and select using unityengine.networking the shortcut to bring up the libel menu is all enter unless in windows this line of code will instantiate a web request it will be stored in the triple w variable next we set a content type for the request letting unity now we are dealing with the json response type we are now ready to send the request we simply call send web requests on the instance we call www and grab the resulting operation in a variable we can call operation and i will explain why we are sending the request to the server but we will not get our response back immediately due to network latency therefore we need a way to wait until the response makes it back to unity and then process it fortunately the viral operation exposes our property called izan which will tell us when the operation made it back with the response now we just need a way to wait for that this is where the async magic comes into play the logic in this block says wait until the operation is done but as you can see the compiler does not immediately recognize task all the way away for task we just need the correct assembly added at the top the away keyword provides a non-blocking way to start a task then continue execution when the task completes our method just need the async modifier added to its signature that signals to the compiler that this method contains an await statement that it has asynchronous operations okay that was the most challenging part of the code we are ready to process the response for now we can simply mark it as success or failure if success the console will print json response otherwise an error will be output instead to quickly call this method for testing we will mark it as a context menu one last important detail we need to inject a proper url that returns suggestion object i will use this free and public api feel free to use what you prefer is set if i test mine in the browser i can see the json object returned that's it let's make sure our code compiles in unity first create an empty game object in the scene and attach the text controller script to it in the inspector click on the button with the three dots that will bring up the options sub menu for our test controller component you will find our test get sub menu item at the very bottom which was generated for us by adding the context menu attribute on our method go ahead and click it and check out the console nice success now click on that log and see the resulting json printed choose the same json we got back in the browser ok cool that's awesome at the moment we are only retrieving the json as a string but to use its content in our code we have to deserialize it first let's modify our code slightly and introduce a try catch block the purpose of a try catch block is to catch and handle an exception generated by a working code the try block contains the guarded code that may cause an exception in our case the json visualization step there are many json libraries out there i will use one of the most common neutrons of jason more specifically a version that fully supports all unity platforms i'll leave the link to the github repo in the description the install process is very straightforward by using its package installer feel free to use the other installation option or simply use a differentiation library we will make sure that our code is very flexible to adapt once newton's soft digestion is installed we can add the respective assembly now we need to map the json response to a class this class will need property names matching those within the json object once done we just let the json library know which type of object will be deserializing okay time to test our code we are going to use visual studio's debugger so we can inspect the resulting instance of the class user we could continue to use debug lock but the debugger is way more convenient by far to do this go to visual studio and click the attach to unity button at the top for this to work unity must be open visual studio will build your solution and then enter into debug mode the bottom bar of the window will become orange let's place a breakpoint at the line by clicking left of the line number go back to unity and execute our code by using the context menu once again visual studio will stop execution once the program reaches that line of code and now we can inspect the state of our code in real time let's step over to the following line so the object is deserialized you can step over by clicking on the step over button or you can use the keyboard shortcut f10 if you hover over the result variable the debugger will show you its content we got all the correct data these utilize another option is to open the locals window the locals window will show all available instances up to this point of the execution up to this point all the code is inside our test controller let's first encapsulate this into its own class let's call it happy http client trust me you will be happy to reduce this code on and on this class does not inherit from amount of behavior this will make it possible to instantiate it from anywhere the first step is to copy and paste our code into a new method named get the difference is that the url will be passed from outside as a parameter make sure to add all the necessary assemblies at the top of the class now let's get back to test controller and refactor it first we need to create an instance of the happy http client and now we can call get on that instance and pass the url we will get the response back and that's it for now let's give it a quick test yep same result but something is odd here our happy http client class should not know the user class let's remove that dependency by using generics don't worry i know generics might sound a bit difficult to understand at first but trust me it will make your code more flexible let's replace the user reference with t result type as the return type and also requires to pass its signature the name t result type is irrelevant and you can name your generic variable as you wish i prefer to choose a self-explanatory name two more things update reference in digestion converse step and return default instead of no as the compiler has no guarantee this is a nullable type yet brilliant it compiles let's get back to test controller and letter get method now the result type user time to test it excellent seal the same result we still have a problem there is a direct reference to the json serialization library our http client should not know how we are deserializing the response we can see the namespace at the top we need to move that implementation concern out of there we can do so with an interface under strategy pattern i'll explain how an interface name will start by the leading eye letter followed by the actual name of the interface in our case is realization option in the declaration users need the interface keyword instead of class using interfaces is an excellent way of keeping our code decoupled an interface is nothing more than a contract between an object and its user a contract with an agreed collection of method and property declarations in our contract we will declare a deserialized method that receives an argument of type string also the t at the beginning means that we will return an object of type t that is generics again we will tell the compiler that we don't know that type yet the second t is to enforce the color to let the method know which type it needs to return it will be more clear when we use it now let's make an implementation of this we can call it json serialization option this class will implement is realization option immediately the compiler raises an error warning that we are not complying with the contract we need to implement the easyrealize method and match its signature cool the error is gone let's copy and paste the serialization code into here now let's resolve the missing reference you need to solve that json we can replace t result type with t and use the local variable text instead of json response also the missing reference to the system assembly cool that looks better and remove and use assemblies back to happy http client let's add a constructor so we can inject the interface we will store its value in a private read-only field you can let visual studio add added for you and this is just me preferring underscore for private field names cool now we can use it but before that let's wrap the async code within a try catch a handle exception inside an async method could be swallowed and die silently which would end up in your program not behaving as expected ok now we can remove visualization responsibility by using the interface see how we let know that this utilized method that we will be dealing with the response of type t result type which is also generic but it will be passed by the color of the get method a bit of cleanup in the exception log and now we can safely remove the dependency to the need to unsolved.json namespace at the top ah one more thing we can move the content type string to the iserialization option the string is directly related to the serialization strategy that we choose so let's add a read-only property of type string to our contract the compiler raises the error of the missing property let's add it and just set its value back to the get method we can now use the interface to set the content type of the request let's clean it up a bit we don't need to keep a reference to the json string instead we just pass it directly to the deserialize method okay we are done in this class back to testcontroller we have an error telling us that we are not passing a serialization option in the constructor so let's create it and pass it that's it let's test it same result great we made it you can continue improving the http client class by adding a post method with post you will need more settings like authentication headers etc for that you can continue to use the strategy pattern leave a comment and let me know what you come up with good luck if you like this video please subscribe to my channel also let me know which topic you would like me to cover in the next video this was carlos thanks for watching
Info
Channel: Coding with Carlos
Views: 5,405
Rating: undefined out of 5
Keywords: Unity3d, UnityWebRequest, C#, HTTP, tutorial, async, restful, get
Id: Yp8uPxEn6Vg
Channel Id: undefined
Length: 15min 48sec (948 seconds)
Published: Sun Apr 18 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.