Inside Unity I had prefabs, it calls "PropertyContainer" it filled with 2 text game object(Room_Type and Room_Qty) that I want to change it dynamically from my database. I had try to learn and watch any youtube tutorial and on the internet. After several weeks try searching and watching I still can't figure it out how to implementing into my code.
Below is my code that I got from several tutorial and some cases on the internet.
First code, is my php code that I used:
<?php
require 'Connection.php';
//Check Connection
if ($conn->connect_error){
die("Connection Failed: " . $conn->connect_error);
}
//Create Variable Submitted
$ID_Type = 2;
$sql = "SELECT Room_Type, Room_Qty FROM House WHERE ID_Type = '" . $ID_Type . "'";
$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();?>
It calls GetStockHouse_RoseType.php, After it is successfully to show my value to be a Json file then the next step I need to call it into my Unity. There are several code that I'm used in unity.
Second code, using C# it called Web.cs:
public IEnumerator GetPropertyStock(string ID_Type, Action<string> callback)
{
WWWForm form = new WWWForm();<br>
form.AddField("ID_Type", ID_Type);
using (UnityWebRequest www = UnityWebRequest.Get("http://localhost/xxxDB/GetStockHouse_RoseType.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);
}
}
}
Third code, called Items.cs:
Action<string> _createItemsCallback;
// Use this for initialization
void Start () {
_createItemsCallback = (jsonArrayString) => {
StartCoroutine(CreateItemsRoutine(jsonArrayString));
};
CreateItems();
}
// Update is called once per frame
public void CreateItems() {
StartCoroutine(Main.Instance.Web.GetPropertyStock(_createItemsCallback));
}
IEnumerator CreateItemsRoutine(string jsonArrayString)
{
//Parsing json array string as an array
JSONArray jsonArray = JSON.Parse(jsonArrayString) as JSONArray;
for (int i = 0; i < jsonArray.Count; i++)
{
//Create local variables
bool isDone = false; //Are we done downloading?
string ID_Type = jsonArray[i].AsObject["ID_Type"];
JSONObject itemInfoJson = new JSONObject();
//Create a callback to get the information from Web.cs
Action<string> getItemInfoCallback = (itemInfo) =>
{
isDone = true;
JSONArray tempArray = JSON.Parse(itemInfo) as JSONArray;
itemInfoJson = tempArray[0].AsObject;
};
StartCoroutine(Main.Instance.Web.GetPropertyStock(ID_Type, getItemInfoCallback));
//Wait until the callback is called from the Web (info finished downloading).
yield return new WaitUntil(() => isDone == true);
//Instantiate GameObject (item prefab).
GameObject item = Instantiate(Resources.Load("Prefabs/PropertiContainer") as GameObject);
item.transform.SetParent(this.transform);
item.transform.localScale = Vector3.one;
item.transform.localPosition = Vector3.zero;
//Fill Information.
item.transform.Find("Room_Type").GetComponent<Text>().text = itemInfoJson["Room_Type"];
item.transform.Find("Room_Qty").GetComponent<Text>().text = itemInfoJson["Room_Qty"];
}
yield return null;
}
Fourth code, called Main.cs:
public static Main Instance;
public Web Web;
// Use this for initialization
void Start () {
Instance = this;
Web = GetComponent<Web>();
}
NOTES:The second and the fourth code is set in into one(1) Empty Object on Unity while the third code is set in the parents that called PropertyContainer.
Bellow is the picture from my Unity:
Picture No. 1) Main.cs & Web.cs set it into one Empty Object and also look oh my Game object for Room_Type and Room_Qty.
Main.cs & Web.cs
Item.cs
Unity File
What I expected is two (2) text Game Objects (Room_Type and Room_Qty) on PropertyContainer can change into my .php code. I hope all that information can fully understand.
Related
This feels like a simple question and I feel like I am overthinking it. I am doing an AWS project that will compare face(s) on an image to a database (s3bucket) of other faces. So far, I have a lambda function for the comparefacerequest, a class library which invokes the function, and an UWP that inputs the image file and outputs a result. It has worked so far being based on boolean (true or false) functions, but now I want it to instead return what face(s) are recognized via an array. I struggling at implementing this.
Below is my lambda function. I have adjusted the task to be an Array instead of a bool and changed the return to be an array. At the bottom, I have created a global variable class with a testing array so I could attempt to reference the array elsewhere.
public class Function
{
//Function
public async Task<Array> FunctionHandler(string input, ILambdaContext context)
{
//number of matched faces
int matched = 0;
//Client setup
var rekognitionclient = new AmazonRekognitionClient();
var s3client = new AmazonS3Client();
//Create list of target images
ListObjectsRequest list = new ListObjectsRequest
{
BucketName = "bucket2"
};
ListObjectsResponse listre = await s3client.ListObjectsAsync(list);
//loop of list
foreach (Amazon.S3.Model.S3Object obj in listre.S3Objects)
{
//face request with input and obj.key images
var comparefacesrequest = new CompareFacesRequest
{
SourceImage = new Image
{
S3Object = new S3Objects
{
Bucket = "bucket1",
Name = input
}
},
TargetImage = new Image
{
S3Object = new S3Objects
{
Bucket = "bucket2",
Name = obj.Key
}
},
};
//compare with confidence of 95 (subject to change) to current target image
var detectresponse = await rekognitionclient.CompareFacesAsync(comparefacesrequest);
detectresponse.FaceMatches.ForEach(match =>
{
ComparedFace face = match.Face;
if (match.Similarity > 95)
{
//if face detected, raise matched
matched++;
for(int i = 0; i < Globaltest.testingarray.Length; i++)
{
if (Globaltest.testingarray[i] == "test")
{
Globaltest.testingarray[i] = obj.Key;
}
}
}
});
}
//Return true or false depending on if it is matched
if (matched > 0)
{
return Globaltest.testingarray;
}
return Globaltest.testingarray;
}
}
public static class Globaltest
{
public static string[] testingarray = { "test", "test", "test" };
}
Next, is my invoke request in my class library. It has so far been based on the lambda outputting a boolean result, but I thought, "hey, it is parsing the result, it should be fine, right"? I do convert the result to a string, as there is no GetArray, from what I know.
public async Task<bool> IsFace(string filePath, string fileName)
{
await UploadS3(filePath, fileName);
AmazonLambdaClient client = new AmazonLambdaClient(accessKey, secretKey, Amazon.RegionEndpoint.USWest2);
InvokeRequest ir = new InvokeRequest();
ir.InvocationType = InvocationType.RequestResponse;
ir.FunctionName = "ImageTesting";
ir.Payload = "\"" + fileName + "\"";
var result = await client.InvokeAsync(ir);
var strResponse = Encoding.ASCII.GetString(result.Payload.ToArray());
if (bool.TryParse(strResponse, out bool result2))
{
return result2;
}
return false;
}
Finally, here is the section of my UWP where I perform the function. I am referencing the lambda client via "using Lambdaclienttest" (name of lamda project, and this is its only instance I use the reference though). When I run my project, I do still get a face detected when it should, but the Globaltest.testingarray[0] is still equal to "test".
var Facedetector = new FaceDetector(Credentials.accesskey, Credentials.secretkey);
try
{
var result = await Facedetector.IsFace(filepath, filename);
if (result)
{
textBox1.Text = "There is a face detected";
textBox2.Text = Globaltest.testingarray[0];
}
else
{
textBox1.Text = "Try Again";
}
}
catch
{
textBox1.Text = "Please use a photo";
}
Does anyone have any suggestions?
I'm trying to Load AssetBunddle form Android Folder from in Unity.
but it doesn't work...
I thought URL is wrong.
Changed URL many time, recommended or specification of Unity document but every case failed
Here is My Code.
public string BundleURL;
public int version;
void Start()
{
CleanCache();
BundleURL = "file://"+Application.persistentDataPath + " /BundleTest";
StartCoroutine(LoadAssetBundle(BundleURL));
version = 0;
}
I thought BundleURL is wrong or has problem
IEnumerator LoadAssetBundle(string BundleURL)
{
//BundleURL = "file://" + path ;
GameObject obj;
//ARLog.d ("LoadAssetBundle" + BundleURL);
while (!Caching.ready)
yield return null;
using (WWW www = WWW.LoadFromCacheOrDownload(BundleURL, version))
{
yield return www;
AssetBundle bundle = www.assetBundle;
String[] mPath = bundle.GetAllAssetNames();
String bundleName = null;
if (bundleName != null)
{
AssetBundleRequest request = bundle.LoadAssetAsync(bundleName, typeof(GameObject));
yield return request;
obj = Instantiate(request.asset) as GameObject;
bundle.Unload(false);
www.Dispose();
}
}
}
}
I want Instance Model in my Scene(from BundelTest Folder in Androind)
You have an additional space there in
BundleURL = "file://"+Application.persistentDataPath + " /BundleTest";
in " /BundleTest"!
For paths in general you allways rather should use Path.Combine instead of manually concatenating strings:
BundleURL = Path.Combine(Application.persistentDataPath,"BundleTest");
this makes sure that in the resulting path automatically the correct path separator (/ or \) for the according atrget system is used.
Than note that WWW is obsolete and not that fast → you should have a look at AssetBundle.LoadFromFileAsync there is an example of how to use it
public void IEnumerator LoadBundle()
{
var bundleLoadRequest = AssetBundle.LoadFromFileAsync(Path.Combine(Application.streamingAssetsPath, "BundleTest"));
yield return bundleLoadRequest;
var myLoadedAssetBundle = bundleLoadRequest.assetBundle;
if (myLoadedAssetBundle == null)
{
Debug.Log("Failed to load AssetBundle!");
yield break;
}
var assetLoadRequest = myLoadedAssetBundle.LoadAssetAsync<GameObject>("MyObject");
yield return assetLoadRequest;
GameObject prefab = assetLoadRequest.asset as GameObject;
Instantiate(prefab);
myLoadedAssetBundle.Unload(false);
}
If you prefer synchronous loading checkout AssetBundle.LoadFromFile instead.
Another note in general: if you are using
using (WWW www = WWW.LoadFromCacheOrDownload(BundleURL, version))
{
....
}
you don't have to use Dispose as it is disposed at the and of the using block automatically.
This question already has an answer here:
You are using download over http. Currently Unity adds NSAllowsArbitraryLoads to Info.plist to simplify transition
(1 answer)
Closed 4 years ago.
I am uploading data to database using WWW.
I have two data classes for data object.
[Serializable]
public class pushdatawrapper{
public string email;
public pushdata[] shotsArray=new pushdata[1];
}
[Serializable]
public class pushdata{
public string timehappened;
public string clubtype;
public pushdata(string timestamp_,string clubtype_)
{
timehappened = timestamp_;
clubtype = clubtype_;
}
}
Loading Json array of data object to database, I tried two approaches.
The first one was ok, but the second one is always failed at calling StartCoroutine function.
First approach
public class BLEBridge : MonoBehaviour {
void Start () {
pushdata_ pdata = new pushdata_("123123123123.0","15","123.0","123.0", "123.0", "123.0","123.0", "123.0","123.0","123.0","123.0","123.0", "First");
pushdatawrapper_ pw = new pushdatawrapper_ ();
pw.email = "test#gmail.com";
pw.shotsArray[0] = pdata;
StartCoroutine (PushData_ (pw));
}
private IEnumerator PushData_(pushdatawrapper_ pdata){
WWW www;
Hashtable postHeader = new Hashtable();
postHeader.Add("Content-Type", "application/json");
string dataToJason = JsonUtility.ToJson(pdata);
Debug.Log ("dataToJason " + dataToJason);
// convert json string to byte
var formData = System.Text.Encoding.UTF8.GetBytes(dataToJason);
www = new WWW("http://rmotion.rapsodo.com/api/push/new", formData, postHeader);
StartCoroutine(WaitForRequest(www));
return www;
}
IEnumerator WaitForRequest(WWW data)
{
yield return data; // Wait until the download is done
if (data.error != null)
{
Debug.Log("There was an error sending request: " + data.text);
}
else
{
Debug.Log("WWW Request: " + data.text);
}
}
}
This first method is always ok.
But in actual implementation, I need to upload data from a static function. Those private IEnumerator PushData_(pushdatawrapper_ pdata) and IEnumerator WaitForRequest(WWW data) can't be static.
So what I did was
I made a separate class as
public class UploadData: MonoBehaviour{
public void uploadindividualshot(pushdatawrapper pw){
StartCoroutine (PushData (pw));
}
private IEnumerator PushData(pushdatawrapper pdata){
WWW www;
Hashtable postHeader = new Hashtable();
postHeader.Add("Content-Type", "application/json");
string dataToJason = JsonUtility.ToJson(pdata);
Debug.Log ("dataToJason " + dataToJason);
// convert json string to byte
var formData = System.Text.Encoding.UTF8.GetBytes(dataToJason);
Debug.Log ("before www ");
www = new WWW("http://rmotion.rapsodo.com/api/push/new", formData, postHeader);
Debug.Log ("after new ");
StartCoroutine(WaitForRequest(www));
Debug.Log ("after WaitForRequest ");
return www;
}
IEnumerator WaitForRequest(WWW data)
{
Debug.Log ("start pushing ");
yield return data; // Wait until the download is done
if (data.error != null)
{
Debug.Log("There was an error sending request: " + data.text);
}
else
{
Debug.Log("WWW Request: " + data.text);
}
}
}
Then call the instance of the class from static method as
public class BLEBridge : MonoBehaviour {
void Start(){}
public unsafe static void GetGolfREsult()
{
pushdata pdata = new pushdata("123123123123.0","15","123.0","123.0", "123.0", "123.0","123.0", "123.0","123.0","123.0","123.0","123.0", "First");
pushdatawrapper pw = new pushdatawrapper();
pw.email = Login.loginName;
pw.shotsArray[0] = pdata;
UploadData up = new UploadData ();
up.uploadindividualshot (pw);
}
}
I always have error as
after new
UploadData:PushData(pushdatawrapper)
BLEBridge:GetGolfREsult()
(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)
libc++abi.dylib: terminating with uncaught exception of type Il2CppExceptionWrapper
2018-04-29 17:25:25.565292+0800 RMotion[270:7241] You are using download over http. Currently Unity adds NSAllowsArbitraryLoads to Info.plist to simplify transition, but it will be removed soon. Please consider updating to https.
The program has error at StartCoroutine(WaitForRequest(www));
What is wrong with second approach?
In unity calling this line of code automatically start http request
WWW www = new WWW("url");
yield is just the convenience way to tell the coroutine to wait for the process to finish. Don't separate your calls in 2 IEnumerator.
private IEnumerator PushData_(pushdatawrapper_ pdata){
WWW www;
Hashtable postHeader = new Hashtable();
postHeader.Add("Content-Type", "application/json");
string dataToJason = JsonUtility.ToJson(pdata);
Debug.Log ("dataToJason " + dataToJason);
// convert json string to byte
var formData = System.Text.Encoding.UTF8.GetBytes(dataToJason);
www = new WWW("http://rmotion.rapsodo.com/api/push/new", formData, postHeader)
Debug.Log ("start pushing ");
yield return www; // Wait until the download is done
if (www.error != null)
{
Debug.Log("There was an error sending request: " + www.text);
}
else
{
Debug.Log("WWW Request: " + www.text);
}
}
And I don't see any use of pointer in your static method so why did you use the unsafe keyword?
I am creating a HoloLens app using Unity which has to take data from a REST API and display it.
I am currently using WWW datatype to get the data and yield return statement in a coroutine that will be called from the Update() function. When I try to run the code, I get the latest data from the API but when someone pushes any new data onto the API, it does not automatically get the latest data in real time and I have to restart the app to see the latest data.
My Code:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
public class TextChange : MonoBehaviour {
// Use this for initialization
WWW get;
public static string getreq;
Text text;
bool continueRequest = false;
void Start()
{
StartCoroutine(WaitForRequest());
text = GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
}
private IEnumerator WaitForRequest()
{
if (continueRequest)
yield break;
continueRequest = true;
float requestFrequencyInSec = 5f; //Update after every 5 seconds
WaitForSeconds waitTime = new WaitForSeconds(requestFrequencyInSec);
while (continueRequest)
{
string url = "API Link goes Here";
WWW get = new WWW(url);
yield return get;
getreq = get.text;
//check for errors
if (get.error == null)
{
string json = #getreq;
List<MyJSC> data = JsonConvert.DeserializeObject<List<MyJSC>>(json);
int l = data.Count;
text.text = "Data: " + data[l - 1].content;
}
else
{
Debug.Log("Error!-> " + get.error);
}
yield return waitTime; //Wait for requestFrequencyInSec time
}
}
void stopRequest()
{
continueRequest = false;
}
}
public class MyJSC
{
public string _id;
public string author;
public string content;
public string _v;
public string date;
}
This is happening because resources caching is enabled on the Server.
Three possible solutions I know about:
1.Disable resources caching on the server. Instructions are different for every web server. Usually done in .htaccess.
2.Make each request with unique timestamp. The time should in Unix format.
This method will not work on iOS. You are fine since this is for HoloLens.
For example, if your url is http://url.com/file.rar, append ?t=currentTime at the end. currentTime is the actual time in Unix Format.
Full example url: http://url.com/file.rar?t=1468475141
Code:
string getUTCTime()
{
System.Int32 unixTimestamp = (System.Int32)(System.DateTime.UtcNow.Subtract(new System.DateTime(1970, 1, 1))).TotalSeconds;
return unixTimestamp.ToString();
}
private IEnumerator WaitForRequest()
{
string url = "API Link goes Here" + "?t=" + getUTCTime();
WWW get = new WWW(url);
yield return get;
getreq = get.text;
//check for errors
if (get.error == null)
{
string json = #getreq;
List<MyJSC> data = JsonConvert.DeserializeObject<List<MyJSC>>(json);
int l = data.Count;
text.text = "Data: " + data[l - 1].content;
}
else
{
Debug.Log("Error!-> " + get.error);
}
}
3.Disable Cache on the client side by supplying and modifying the Cache-Control and Pragma headers in the request.
Set Cache-Control header to max-age=0, no-cache, no-store then set Pragma header to no-cache.
I suggest you do this with UnityWebRequest instead of the WWW class. First, Include using UnityEngine.Networking;.
Code:
IEnumerator WaitForRequest(string url)
{
UnityWebRequest www = UnityWebRequest.Get(url);
www.SetRequestHeader("Cache-Control", "max-age=0, no-cache, no-store");
www.SetRequestHeader("Pragma", "no-cache");
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
Debug.Log("Received " + www.downloadHandler.text);
}
}
Currently I'm working on a custom importer for Ironpython, which should add an abstraction layer for writing custom importer. The abstraction layer is an IronPython module, which bases on PEP 302 and the IronPython zipimporter module. The architecture looks like this:
For testing my importer code, I've written a simple test package with modules, which looks like this:
/Math/
__init__.py
/MathImpl/
__init__.py
__Math2__.py
/Math/__init__.py:
print ('Import: /Math/__init__.py')
/Math/MathImpl/__init__.py:
# Sample math package
print ('Begin import /Math/MathImpl/__init__.py')
import Math2
print ('End import /Math/MathImpl/__init__.py: ' + str(Math2.add(1, 2)))
/Math/MathImpl/Math2.py:
# Add two values
def add(x, y):
return x + y
print ('Import Math2.py!')
If i try to import MathImpl like this in a script: import Math.MathImpl
My genericimporter get's called and searchs for some module/package in the find_module method. Which returns an instance of the importer if found, else not:
public object find_module(CodeContext/*!*/ context, string fullname, params object[] args)
{
// Set module
if (fullname.Contains("<module>"))
{
throw new Exception("Why, why does fullname contains <module>?");
}
// Find resolver
foreach (var resolver in Host.Resolver)
{
var res = resolver.GetModuleInformation(fullname);
// If this script could be resolved by some resolver
if (res != ResolvedType.None)
{
this.resolver = resolver;
return this;
}
}
return null;
}
If find_module is called the first time,fullname contains Math, which is ok, because Math should be imported first. The second time find_module is called, Math.MathImpl should be imported, the problem here is, that fullname has now the value <module>.MathImpl, instead of Math.MathImpl.
My idea was, that the module name (__name__) is not set correctly when Math was imported, but i set this in any case when importing the module in load_module:
public object load_module(CodeContext/*!*/ context, string fullname)
{
string code = null;
GenericModuleCodeType moduleType;
bool ispackage = false;
string modpath = null;
PythonModule mod;
PythonDictionary dict = null;
// Go through available import types by search-order
foreach (var order in _search_order)
{
string tempCode = this.resolver.GetScriptSource(fullname + order.Key);
if (tempCode != null)
{
moduleType = order.Value;
code = tempCode;
modpath = fullname + order.Key;
Console.WriteLine(" IMPORT: " + modpath);
if ((order.Value & GenericModuleCodeType.Package) == GenericModuleCodeType.Package)
{
ispackage = true;
}
break;
}
}
// of no code was loaded
if (code == null)
{
return null;
}
var scriptCode = context.ModuleContext.Context.CompileSourceCode
(
new SourceUnit(context.LanguageContext, new SourceStringContentProvider(code), modpath, SourceCodeKind.AutoDetect),
new IronPython.Compiler.PythonCompilerOptions() { },
ErrorSink.Default
);
// initialize module
mod = context.ModuleContext.Context.InitializeModule(modpath, context.ModuleContext, scriptCode, ModuleOptions.None);
dict = mod.Get__dict__();
// Set values before execute script
dict.Add("__name__", fullname);
dict.Add("__loader__", this);
dict.Add("__package__", null);
if (ispackage)
{
// Add path
string subname = GetSubName(fullname);
string fullpath = string.Format(fullname.Replace(".", "/"));
List pkgpath = PythonOps.MakeList(fullpath);
dict.Add("__path__", pkgpath);
}
else
{
StringBuilder packageName = new StringBuilder();
string[] packageParts = fullname.Split(new char[] { '/' });
for (int i = 0; i < packageParts.Length - 1; i++)
{
if (i > 0)
{
packageName.Append(".");
}
packageName.Append(packageParts[i]);
}
dict["__package__"] = packageName.ToString();
}
var scope = context.ModuleContext.GlobalScope;
scriptCode.Run(scope);
return mod;
}
I hope some one has an idea, why this happens. A few line which also may cause the problem are:
var scriptCode = context.ModuleContext.Context.CompileSourceCode
(
new SourceUnit(context.LanguageContext, new SourceStringContentProvider(code), modpath, SourceCodeKind.AutoDetect),
new IronPython.Compiler.PythonCompilerOptions() { },
ErrorSink.Default
);
and
mod = context.ModuleContext.Context.InitializeModule(modpath, context.ModuleContext, scriptCode, ModuleOptions.None);
Because i don't know, whether creating a module this way is completly correct.
The problem can be reproduced downloading this project/branch: https://github.com/simplicbe/Simplic.Dlr/tree/f_res_noid and starting Sample.ImportResolver. An exception in find_module will be raised.
Thank you all!
This problem is solved. Modpath what not allowed to contains /. In general only chars were allowed, which also can be in a file-name.
Maybe this is helpful for someone else...