Skip to main content

Unity Get Post web requests - Technoob Technology

Web requests in unity are super easy to use. We gonna use the UnityWebRequest class as the WWW class is deprecated now. UnityWebRequest class can be used for both Get and Post methods. The 'UnityEngine.Networking' namespace is required to work with UnityWebRequests. 


unity get post web requests - technoob.me


This tutorial is made with some simple UI elements. First Let's see how the GET method works.


01. UnityWebRequest.GET

We use this method to receive data from the server as normal get requests. Using coroutines in web requests is mandatory as we have to wait until the download is complete before showing the results, and the coroutines make this much easier. A simple button calls the method and a text element will show the result.


unity get post web requests - technoob.me

The script contains a reference to the text element and the string URL of your PHP file. 


unity get post web requests - technoob.me



When the button is pressed the button executes the ButtonGetData method and that method simply starts the GetData coroutine. We use the using keyword as this data is disposable. We create a web request and call the 'SendWebRequest()' method with the yield return keyword to wait till the download is complete before executing the rest. If the web request throws an error a debug.log or a log warning  notifies that there's an error. Finally, we access the download handler of the web request class and get the result text of it and then we set our text elements text to the result text.


unity get post web requests - technoob.me

Our PHP code is very simple and when we run the script the following result is generated.


unity get post web requests - technoob.me



02.UnityWebRequest.Post

This is much like the get method. We use the 'UnityWebRequest.post' and as the second parameter, we have to feed an instance of the WWWform class. Adding data fields is easy and we can add as many as we want in the www form in order to send those data to the server. 'WWWForm.AddField' takes usually a string key and a string text as parameters. This data can be accessed from the PHP file using the '$_POST' keyword.  


unity get post web requests - technoob.me


An Input field is used to enter the data and the text field to show the result.


unity get post web requests - technoob.me


unity get post web requests - technoob.me


When the button is pressed following result is generated according to the input.


unity get post web requests - technoob.me



When we look at the use cases of these WebRequests the most common use cases are to login to the game server and to receive game data from the server. Let's try out a simple example. Imagine that we have a MySQL database which contains the details of some heroes. 

We can send the hero name in a post method and run some simple MySQL queries and assign the results to this hero name, damage and armor values. 




using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class ConnectionController : MonoBehaviour
{

    public Text heroNameText;
    public Text damageText;
    public Text armourText;

    public InputField inputField;
    
    private const string URL = "http://localhost/testserver.php";
    
    
    public void ButtonGetData()
    {
        StartCoroutine(GetData());
    }

    IEnumerator GetData()
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(URL))
        {
            yield return webRequest.SendWebRequest();
            
            if (webRequest.isHttpError || webRequest.isNetworkError)
            {
                Debug.Log("Error");
            }
            else
            {
                Debug.Log(webRequest.downloadHandler.text);
                string result = webRequest.downloadHandler.text;
                SplitWords(result);
            }
        }
    }
    
    void SplitWords(string result)
    {
        string[] words = result.Split('|');

        heroNameText.text = $"Hero : {words[0]}";
        damageText.text = $"Damage : {words[1]}";
        armourText.text = $"Armour : {words[2]}";
    }
}


<?php 

$heroName = "SuperMario";
$damage = 56;
$armour = 22;

$output = $heroName."|".$damage."|".$armour;

echo $output;

?>

But here for simplicity, we use only a get method and show the results in the text fields.

The result looks like this.




Related Articles 




Comments

Post a Comment

Popular posts from this blog

How to make a first person character controller - Unity

A first-person character controller script is the starting point of any fps shooter game. Even new Unity game developers tend to write their own fps controller script before learning anything else as it is challenging and very exciting. In this article, we gonna create two simple fps controllers from scratch and will guide you step by step on how it works. First, let's understand the basic concept of an fps controller. You should have a rotating camera that rotates in the x-axis to look up and down and the character should rotate on the y-axis to look around. There are two ways to create an fps controller in the Unity Engine.  Using Character controller component Using the RigidBody component Both have different advantages and disadvantages when using them. It depends on your game to select the best fps controller according to your needs.  Character controller based fps controller Pros: Is grounded check is built-in Has its own methods to move the ...

How to make an Advanced Audio Manager for Unity - Technoob Technology

Unity engine gives us a good control on audio clips we use, But the problem is when we add several audio sources for several audio clips it's gonna get hard to control them all. And if you want to make some changes to only one audio source you have to find it first.  This will become a mess if you gonna work with more than 10 audio clips. In this case, we can Create an AudioManager and include all the audio clips in it and make some static methods to play, pause the audio from other scripts. This Audio Manager is written in C# and if you use unity-script you have to convert this into unity script first. In this tutorial, we gonna create an audio manager which contains 7 methods. 1.Play 2.Pause 3.Unpause 4.Stop 5.FadeIn 6.FadeOut 7.lower volume for a duration First, we need a Custom class which contains some strings, floats, bools and an audio clip. This class is not derived from unity mono behavior so we should add [System.Serializable] t...

How to make an Event-System for unity - Technoob Technology

First, What is an Event-System? An Event-System is a collection of scripts we use to send messages between game objects without linking them through the Unity inspector. The best use of this is when you want to connect a game object of the scene to a prefab. Unity Engine doesn't allow us to do that through the inspector and the best way to get this done is by using an Event-System. What if you have 50 enemies in the game and you want to notify them all when the player dies. Without an Event-System we have to connect all the enemies to a manager or some kind of a script to do that... Think about having an array of 50 enemies. This can be solved easily using an Event-System. We will do a basic example of using this event system in the end of the article. Well, now we know the advantages of using an Event-System. Lets start coding our own simple Event-System. First we have to get an idea on how this works. First, a script in the scene raises an event using a static method o...