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;
}
}
}
}`