Basic Unity and Client-Server Request-Response with PHP

In order to make our Unity game connected to the online world, it must be able to send requests to and get responses from our server.

In this tutorial you will see the basic way to make our game able to communicate to PHP server side script.

Server side script in PHP :

<?php
    if(isset($_POST["postdata"])){
        echo "Your POST data is " . $_POST["postdata"];
    }
    if(isset($_GET["getdata"])){
        echo "Your GET data is " . $_GET["getdata"];
    }
?>

Unity C# GET Script :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class GET : MonoBehaviour
{

    void Start()
    {
        StartCoroutine(GetText());
    }

    IEnumerator GetText()
    {
        using (UnityWebRequest www = UnityWebRequest.Get("https://zk.ciihuy.com/tutorials/unitypostget/serverscript.php?getdata=HelloWorld!"))
        {
            yield return www.Send();

            if (www.isNetworkError || www.isHttpError)
            {
                Debug.Log(www.error);
            }
            else
            {
                string responseText = www.downloadHandler.text;
                Debug.Log("Response Text from the server = " + responseText);
            }
        }
    }
}

Unity C# POST script :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public class POST : MonoBehaviour {

    void Start()
    {
        StartCoroutine(SendRequest());
    }

    IEnumerator SendRequest()
    {
        WWWForm form = new WWWForm();
        form.AddField("postdata", "HelloWorld!");
        using (UnityWebRequest www = UnityWebRequest.Post("https://zk.ciihuy.com/tutorials/unitypostget/serverscript.php", form))
        {
            www.downloadHandler = new DownloadHandlerBuffer();
            yield return www.SendWebRequest();

            if (www.isNetworkError)
            {
                Debug.Log(www.error);
            }
            else
            {
                string responseText = www.downloadHandler.text;
                Debug.Log("Response Text from the server = " + responseText);
            }
        }
    }
}

Getting boored? Why not playing a game?

Power Block

Tiki Solitaire

Pet Connect

Cake Shop

Jewels Blitz 3

Forest Match

Bike Racing

Aquador

Solitaire Swift

Bubble Shooter Classic HD

Black and white snake

Leave a Reply

Your email address will not be published. Required fields are marked *