1

For summarize my problem is, I want to add some informations from my database into my text Game Object at unity. Several questions that came up into my mind is:

1.) Do I need my data to be encoded on JSON in my PHP file? and of course,

2.) How to add the value into my text game object.

Below is what I had done with the code:

1.) I had some datas that has been encoded with JSON on my PHP file, just two types of data which is Room_Type and Room_Qty.

2.) I already call it in unity using IEnumerator and try to StartCoroutine, it works and it showed my JSON data. I already debug it and it showing somethings like this:
[{"Room_Type":"Melati_Room","Room_Qty":"6"}]
UnityEngine.Debug:Log(Object)
c__Iterator0:MoveNext() (at Assets/Web.cs:35)
UnityEngine.SetupCoroutine:InvokeMoveNext(IEnumerator, IntPtr)

3.) It showed Melati_Room for Room_Type and 6 for Room_Qty. The next step is for Put in "Melati_Room" on my Web.cs IEnumerator into a Text Game Object on Unity named Room_Type and put in 6 on my Web.cs IEnumerator into a Text Game Object on Unity named Room_Qty.

PHP CODE:

<?php
require 'Connection.php';

//Check Connection
if ($conn->connect_error){
    die("Connection Failed: " . $conn->connect_error);
} 

//Create Variable Submitted
$itemID = 2;

$sql = "SELECT Room_Type, Room_Qty FROM BinusApartemenSum WHERE ID_Type = '" . $itemID . "'";
$result = $conn->query($sql);

if ($result->num_rows > 0){
    //Output data of each row.
    $rows = array();

    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    //After the whole array is created.
    echo json_encode($rows);
}else {
    echo "Zero Result";
}

$conn->close();
?>

C# CODE with IEnumerator and StartCoroutine:

// Use this for initialization
void Start () {
    StartCoroutine(GetPropertyStock(""));

}

public IEnumerator GetPropertyStock(string ID_Type) //Action<string> Callback)
{
    WWWForm form = new WWWForm();
    form.AddField("ID_Type", ID_Type);
    //GameObject item = Instantiate(Resources.Load("Prefabs/PropertiContainer") as GameObject);

    //gameObject.GetComponent<GUIText>().guiText = "Room_Type";
    //gameObject.GetComponent<GUIText>().guiText = "Room_Qty";

    using (UnityWebRequest www = UnityWebRequest.Get("http://localhost/MitsalDB/GetStockBA_MawarRoom.php"))
    {
        yield return www.SendWebRequest();

        if (www.isNetworkError || www.isHttpError)
        {
            Debug.Log(www.error);
        }
        else
        {
            //Show results as a text.
            Debug.Log(www.downloadHandler.text);
            string jsonArray = www.downloadHandler.text;
            //Callback(jsonArray);
            //gameObject.GetComponent<GUIText>().guiText = www.text;
        }
    }
}

}`

Faj
  • 75
  • 9

1 Answers1

1

Wanted to answer the last time but you deleted the question ^^


You should have a proper class structure for representing the json data structure. json2csharp is a good tool for auto-generating that structure for you - but make sure to remove all the {get; set;} to turn the properties into fields.

In your case simply something like

[Serializable]
public class RoomData
{
    public string Room_Type;
    public string Room_Qty;
}

and then use JsonUtility.FromJson in order to create a RoomData instance from your json string like

if(string.IsNulOrEmpty(theJsonString) || string.Equals(theJsonString, "Zero Result")
{
    Debug.LogWarning("Internal Server error", this);
    return;
}

var newRoomData = JsonUtility.FromJson<RoomData>(theJsonString);

Then to the question how to display that in Unity .. In the commented line I can see you are using the GUIText ... it's kind of old and you should replace it by the Text components (see the UI Manuals) within your scene. So get the references and simply set their text value accordingly:

// Either reference those in the Inspector
public Text roomTypeText;
public Text roomQtyText;


private void Awake()
{
    // or get them on runtime e.g. using Find with the GameObjects' names
    roomTypeText = Find("Room_Type").GetComponent<Text>();
    roomQtyText= Find("Room_Qty").GetComponent<Text>();
}

...

roomTypeText.text = newRoomData.Room_Type;
roomQtyText.text = newRoomData.Room_Qty;

or if you wanted to display it in one single text use e.g.

aText.text = $"Type:{newRoomData.Room_Type}, Qty:{newRoomData.Room_Qty}";

$"" is a string interpolation .. it is basically more readable equivalent to

aText.text = "Type: " + newRoomData.Room_Type + ", Qty:" + newRoomData.Room_Qty;

In general as commented before: You are still filling WWWForm but not passing it to the WebRequest. You should probably use a UnityWebRequest.Post instead.

Note I also noticed now that your JSON is actually an array. You should refer to Serialize and Deserialize Json and Json Array in Unity for tips how to handle JSON arrays in Unity.

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • Thank you for always answering me! I really appreciate that. Firstly, I came up with simplified the PHP. I just remove the array and just show it after fetch with echo per row like this: `Melati_Room
    6`. I have no intention for `WWWForm` it was just my silly mistake, I already erase that. But I had several question if its not bothered you. 1.) Do I need to start coroutine on my Web.cs? 2.) Is your C# code for display is build on my Web.cs or should I make another ? 3.) How to display my new value with my new PHP. I'm so exhausted with this.. I have no idea how to deal this.
    – Faj Jun 14 '19 at 16:24
  • Glad to help :) To your questions: 1) I don't even see what `Web.cs` is .. but if that's the class holding that `IEnumerator`: You don't have to start it on the same component. Since it is public you can `StartCoroutine` it from anywhere else but the best way is mostly having it running on the same component it belongs to. 2) You didn't have any code for displaying the information so far .. but yes you could simply add the according lines either as callback or to the bottom of your WebRequest IEnumerator. 3) I don't understand .. what is your new PHP and what do you want to display where? – derHugo Jun 14 '19 at 16:36
  • Omg, it makes me more confuse lol. I'm really sorry since this is the first time I wrote the code for displaying the value from my database. I hope you can help to get me trough this. Let me ask you step by step and guiding me until it finished, will you? – Faj Jun 15 '19 at 04:18
  • Btw we are in the different time zone, I'm sorry if I replying you took so long, but I will try to keep up. 1.) My ***PHP CODE*** that I wrote up there is it in the **right structure** and in the **right way** to do it or not? 2.) Next step, is write the C# code right? 3.) If so, Is my ***C# CODE*** that I wrote up there is it in the **right structure** and in the **right way** to do it or not? If not could you make one for me? 4.) What is the next step I should do? – Faj Jun 15 '19 at 04:29
  • Or we could use a **SIMPLE WAY**. Could you make a tutorial for me? hehe. I know it's not gonna be free. I have a little cash and a paypal account and if you had a paypal account I could send a little cash for you. Thank you again for helping me! I really really appreciate since I already exhausted try to solve this problem. I don't really get it how to show my **Database Value** into **Unity Game Object**. I had a few more to show my Database Value. I really need this code. Thx again anyway, let me know your answer. Cheers! – Faj Jun 15 '19 at 04:35
  • Hi, finally I made it by myself. lol. Thx for your help, anyway we are an engineering tho. Cheers! – Faj Jun 16 '19 at 18:44