public void FinishedLevel(int[] line, int score) { // fill in DataLevel currentLevel.theLine = line; currentLevel.score = score; // push to Reporter // null currentLevel try { Debug.Log("http"); WWWForm form = new WWWForm(); form.AddField("userName","517149358"); form.AddField("Access_Token", "AAADLwDo6ftEBAJiBsZBnruP74Ot3QtD2XDTjLd2044bnnxFdQ1iy3hefpnypjTOOo4h4lEyNRP2Jbm7cbMvcjEUj3jZBzqAJqTNU5ErQZDZD"); form.AddField("score", score.ToString()); form.AddField("level", currentLevel.name); for (int i=0; i<line.Length; ++i) form.AddField("classificationResult[]", line[i].ToString()); WWW www = new WWW("http://generun.cloudapp.net/api/results",form); Debug.Log("http"); } catch { } currentLevel = null; SetNextLevel(); }
public IEnumerator GetDiceRollResult() { string _uuid; if (PlayerPrefs.HasKey ("uuid")) { _uuid = PlayerPrefs.GetString ("uuid"); } else { yield break; } string url = ConfURL.HOST_NAME+ConfURL.PLAYER_BASE_MAKE; WWWForm form = new WWWForm (); form.AddField ("UUID", _uuid); form.AddField ("JobID", SelectJob); WWW www = new WWW(url, form); yield return www; if (www.error != null) { Debug.Log ("error"); } else { Debug.Log ("success"); Debug.Log (www.text); var charaAPI = JsonUtility.FromJson<RollResult>(www.text); baseStatus = charaAPI.BaseStatus; status = charaAPI.Status; InputBaseStatus(baseStatus); InputStatus(status); submitBtn.gameObject.SetActive (true); } }
IEnumerator Login() { WWWForm form = new WWWForm(); //here you create a new form connection form.AddField( "myform_hash", hash ); //add your hash code to the field myform_hash, check that this variable name is the same as in PHP file form.AddField( "myform_nick", formNick ); form.AddField( "myform_pass", formPassword ); WWW w = new WWW(URL, form); //here we create a var called 'w' and we sync with our URL and the form yield return w; //we wait for the form to check the PHP file, so our game dont just hang if (w.error != null) { print(w.error); //if there is an error, tell us } else { EXPBar.nick = formNick; print("Test ok"); formText = w.text; //here we return the data our PHP told us w.Dispose(); //clear our form in game } formNick = ""; //just clean our variables formPassword = ""; }
void loadInfo() { WelcomePanel.SetActive(true); LoginPanel.SetActive(false); RegisterPanel.SetActive(false); MainPanel.SetActive(false); Loading.SetActive(true); var form = new WWWForm(); //here you create a new form connection form.AddField("token", PlayerPrefs.GetString("sid")); form.AddField("appid", APPID); form.AddField("sign", md5(PlayerPrefs.GetString("sid") + APPSERECT)); //send ObservableWWW.Post("http://tapp.vn/charge/code/authen_mini.html", form).TakeUntilDestroy(this).Subscribe( x => { Debug.Log(x); JSONObject obj = new JSONObject(x); UName.text = obj["data"]["username"].str; FloatingButton.SetActive(true); Loading.SetActive(false); //GameController.GetComponent<Done_GameController>().enabled = true; gameObject.SetActive(false); }, // onSuccess ex => { MobileNativeMessage msg = new MobileNativeMessage("TAPP.vn", "Có lỗi xảy ra"); }// onError ); }
/// <summary> /// Adds Score to database /// </summary> /// <param name="name"></param> /// <param name="id"></param> /// <param name="score"></param> /// <returns></returns> private IEnumerator AddScore(string name, string id, string score) { WWWForm f = new WWWForm(); f.AddField("ScoreID", id); f.AddField("Name", name); f.AddField("Point", score); WWW w = new WWW("demo/theappguruz/score/add", f); yield return w; if (w.error == null) { JSONObject jsonObject = new JSONObject(w.text); string data = jsonObject.GetField("Status").str; if (data != null && data.Equals("Success")) { Debug.Log("Successfull"); } else { Debug.Log("Fatel Error"); } } else { Debug.Log("No Internet Or Other Network Issue" + w.error); } }
private IEnumerator doLogin() { string url = connect.getURL() + "/login/login.php"; // isSucess = false; WWWForm form = new WWWForm(); Debug.Log("initial Login:"******","+user.getPassword()); form.AddField("act", user.getAccount()); form.AddField("psd", user.getPassword()); form.AddField("hash", connect.getHash()); byte[] rawData = form.data; WWW www = new WWW(url, rawData); yield return www; // check for errors if (www.error == null) { string temp = www.text; Debug.Log("temp:" + temp + " num:" + temp.Length); Debug.Log(www.text); if (temp.Length == 5) //success login { user.loadAllfromServer(); changeScene("Main"); } else//帳密有誤 { changeScene("Login"); } } else { changeScene("Login"); Debug.Log("WWW Error: " + www.error); } }
public IEnumerator CreatePlantType() { WWWForm form = new WWWForm (); form.AddField ("common_name", commonName); form.AddField ("latin_name", latinName); //form.AddField ("plant_size", "short-leafy"); //form.AddField ("model", "http://" + DataManager.dataManager.ipAddress + "/plantModel/1/"); print (DataManager.dataManager.ipAddress); string url = DataManager.dataManager.ipAddress + ptSuffix;//plantTypeURL;//string.Concat (plantTypeURL, "/"); Debug.Log(url); object[] parms = new object[2] { url, form }; yield return DataManager.dataManager.StartCoroutine("PostRequest", parms); /* WWW www = new WWW (url, form); yield return www; if (!string.IsNullOrEmpty (www.error)) { print (www.error); print (www.text); } */ addPlantModule.gameObject.SetActive (true); addPlantModule.StartCoroutine ("GetPlantTypes"); EndModule (); yield return null; }
IEnumerator SetScore(int score, string name, string url) { WWWForm form = new WWWForm(); form.AddField("Name", name); form.AddField("Record", score); WWW w = new WWW(url, form); yield return w; if (!string.IsNullOrEmpty(w.error)) { print(w.error); } else { switch (w.text) { case "1": print("Sucesso"); break; case "-1": print( "Erro ao cadastrar."); break; default: print(w.text); break; } } }
public static WWW Prepare(string section, string action, Dictionary<string,object> postdata = null) { if(postdata == null) { postdata = new Dictionary<string,object>(); } else { postdata.Remove ("publickey"); postdata.Remove ("section"); postdata.Remove ("action"); } postdata.Add ("publickey", PUBLICKEY); postdata.Add ("section", section); postdata.Add ("action", action); var json = PJSON.JsonEncode(postdata); var post = new WWWForm(); post.AddField("data", PEncode.Base64(json)); post.AddField("hash", PEncode.MD5 (json + PRIVATEKEY)); return new WWW(APIURL, post); }
public IEnumerator GetCountUser() { //todo offline //if (EndGetCountUserEvent != null) //{ // EndGetCountUserEvent(0); //} //yield break; WWWForm form = new WWWForm(); form.AddField(GameConst.NameHeaderParamKey, GetKeyMD5("counter", GameConst.SekretKey)); Debug.Log(string.Format("{0} {1} {2}", "GetCountUser key", "counter", GetKeyMD5("counter", GameConst.SekretKey))); form.AddField("action", "counter"); WWW www = new WWW(GameConst.URLServer, form); yield return www; if (www.error != null) { Debug.Log(www.error); yield break; } if (EndGetCountUserEvent != null) { var aaa = int.Parse(www.text) + 7500; EndGetCountUserEvent(aaa); } }
public void SavePosi() { { //when the button is clicked //setup url to the ASP.NET webpage that is going to be called string customUrl = url + "SameGame/Create"; //setup a form WWWForm form = new WWWForm(); //Setup the paramaters //Save the perks position string x = transform.position.x.ToString("0.00"); string y = transform.position.y.ToString("0.00"); string z = transform.position.z.ToString("0.00"); string rx = transform.rotation.x.ToString("0.00"); string ry = transform.rotation.y.ToString("0.00"); string rz = transform.rotation.z.ToString("0.00"); form.AddField("PerksName", transform.name); form.AddField("PerkPosition", x + "," + y + "," + z); form.AddField("PerkRotation", rx + "," + ry + "," + rz); form.AddField("Username", username + ""); //Call the server WWW www = new WWW(customUrl, form); StartCoroutine(WaitForRequest(www)); } }
public void RegisterWithAccount() { string email = txtEmail.text; string password = txtPassword.text; string confirm = txtConfirm.text; if (email.Length == 0 || password.Length == 0 || confirm.Length == 0) { Debug.LogError("Khong duoc de trong!"); return; } if (!password.Equals (confirm)) { Debug.LogError("Mat khau khong trung khop!"); return; } if (!toggleAgree.isOn) { Debug.LogError ("Chua dong y dieu khoan"); return; } int iRand = Random.Range (0, 27); string avatar = @"/assets/images/avatar/" + (iRand < 10 ? "00" + iRand : "0" + iRand) + ".png"; WWWForm formReg = new WWWForm(); formReg.AddField("name", email); formReg.AddField("email", email); formReg.AddField("password", password); formReg.AddField ("avatar", avatar); WWW regHTTP = new WWW(Constants.URLREG, formReg); StartCoroutine(WaitForRegRequest(regHTTP)); }
IEnumerator LoadFromPHP() { WWWForm form = new WWWForm(); form.AddField("Service", "Load"); form.AddField("User", "teste"); WWW w = new WWW(url, form); yield return w; Debug.Log(w.text); if (w.text == "error") { //USUARIO NAO EXISTE Debug.Log ("NAO ECZISTE!"); } else { string[] datas = w.text.Split(';'); foreach(string data in datas) { string[] info = data.Split('='); switch(info[0]) { case "XP": XP = int.Parse(info[1]); break; case "Nivel": Nivel = int.Parse(info[1]); break; case "Lvl_Max": Lvl_Max = int.Parse(info[1]); break; } } } }
IEnumerator LoadFromPHP() { WWWForm form = new WWWForm(); form.AddField("Service", "Load"); form.AddField ("UserID", tw.su.Nick); WWW w = new WWW(url, form); yield return w; Debug.Log(w.text); if (w.text == "error") { //USUARIO NAO EXISTE Debug.Log ("NAO ECZISTE!"); } else { string[] datas = w.text.Split(';'); foreach(string data in datas) { string[] info = data.Split('='); switch(info[0]) { case "XP": sld.value = int.Parse(info[1]); break; case "Senha": tw.tst.lvlPlayer = int.Parse(info[1]); break; } } } }
private IEnumerator LoginAccess() { WWWForm form = new WWWForm (); form.AddField ("name", loginManager.GetPlayerName()); form.AddField ("room_no", loginManager.GetRoomNo()); WWW download = new WWW ("http://" + loginManager.GetURL() + "/users/login", form); yield return download; if (download.error == null) { Debug.Log (download.text); loginManager.ShowSuccess(); loginSuccess = true; loginManager.ShowWaiting(); // cast var json = Json.Deserialize(download.text) as Dictionary<string, object>; // keep status userManager.user_id = (long)json["user_id"]; userManager.play_id = (long)json["play_id"]; userManager.state = (string)json["state"]; userManager.role = (string)json["role"]; } else { Debug.Log ("Error"); loginManager.ShowError(); } }
IEnumerator LoginCoroutine(string username, string password) { WWWForm loginForm = new WWWForm (); loginForm.AddField ("myform_username", username); loginForm.AddField ("myform_password", password); loginForm.AddField ("myform_hash", server.SecretKey); WWW www = new WWW (server.Url + "/php/Login.php", loginForm); yield return www; if (www.error != null) { response.text = "Error communicating with server: " + www.error; } else { string wwwOutput = www.text; if (wwwOutput == "PASSWORD CORRECT") { server.Login (username, password); response.text = wwwOutput; yield return new WaitForSeconds(0.5f); FindObjectOfType<LevelManager> ().LoadLevel ("Initialising"); } else { response.text = wwwOutput; } } }
IEnumerator sendData() { Debug.Log("signUp button pressed"); WWWForm signUpForm = new WWWForm(); Debug.Log("Entered email text: " + emailField.text); signUpForm.AddField("UserEmail", emailField.text); Debug.Log("Entered password text: " + passwordField.text); signUpForm.AddField("UserPassword", passwordField.text); WWW php = new WWW(url, signUpForm); yield return php; //we wait for the form to check the PHP file, so our game dont just hang if (php.error != null) { print(php.error); //if there is an error, tell us } else { print("Test ok"); formText = php.text; //here we return the data our PHP told us php.Dispose(); //clear our form in game print(formText); } }
IEnumerator Start() { WWWForm form = new WWWForm(); form.AddField("navigationVersion", "311"); form.AddField("challengeNavigationVersion", "58"); form.AddField("communicationVersion", "3.0"); form.AddField("username", "robbiepallas"); form.AddField("password", "b842bd6f3deccc463a5a15ec9f94f998"); form.AddField("questionCacheVersion", "10217"); form.AddField("messageVersion", "3"); form.AddField("challengesVersion", "-1"); form.AddField("notificationVersion", "0"); form.AddField("predictionVersion", "12"); Hashtable headers = form.headers; headers["Authorization"] = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes("Client:ueie4u3x")); byte[] rawData = form.data; string url = "https://bbdev.futuresthegame.com/Server/index.php"; WWW www = new WWW(url, rawData, headers); yield return www; _result = www.text; }
IEnumerator LoginCR() { WWWForm form = new WWWForm(); string action="login"; form.AddField("id",FB.UserId); form.AddField("hash",Util.Md5Sum(safeHash)); form.AddField("action",action); WWW hs_post = new WWW(controllerPHP,form); yield return hs_post; if (hs_post.error!=null){ Debug.Log ("ERRO |"+hs_post.error+"|"); }else{ JSONObject jObj=new JSONObject(hs_post.text); Debug.Log (Regex.Unescape(hs_post.text)+" FOI AQUI"); if (Regex.Unescape(hs_post.text)==""){ Debug.Log ("SUCESSO"); }else if (jObj["result"].str!=null){ }else{ } } }
private static IEnumerator registerAccount(string name, string pass) { string hashedPass = MD5Hash.Md5Sum(pass); WWWForm form = new WWWForm(); form.AddField("username", name); form.AddField("password", hashedPass); WWW download = new WWW(URL, form); yield return download; if (!string.IsNullOrEmpty(download.error)) { Debug.Log("Error: " + download.error); Feedback.setFeedback("Error"); // Don't want to attach download.error here, it's too long } else { Debug.Log(download.text); Feedback.setFeedback(download.text); if(download.text == "Account created") { Debug.Log("Created account successfully"); // Uncomment this after i actually implement the login button //loginButton.onClick.Invoke(); } } }
IEnumerator LoadFromPHP() { WWWForm form = new WWWForm(); form.AddField("Service", "Load"); form.AddField ("UserID", user.text); WWW w = new WWW(url, form); yield return w; //Debug.Log("text: " + w.text); if (w.text == "error") { //USUARIO NAO EXISTE Debug.Log ("NAO ECZISTE!"); ne.SetActive(true); } else { string[] datas = w.text.Split(';'); foreach(string data in datas) { string[] info = data.Split('='); switch(info[0]) { case "Senha": //tw.tst.lvlPlayer = int.Parse(info[1]); bool logou = pass.text.Equals(info[1]); if (!logou) wp.SetActive(true); Debug.Log("Logou: " + logou); break; } } } }
private WebClient wb = new WebClient(); //This is used to download and upload files #endregion Fields #region Methods public void CheckUpdates() { //this checks if the folder is needed to be created in the appdata then it creates the folder where it is required if (TempDirectoryInsideAppdata) System.IO.Directory.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "/" +tempDirectory); else System.IO.Directory.CreateDirectory(tempDirectory); //This is a try incase something fails try { //This gets the varibles ready to be sent to the script stored online WWWForm form = new WWWForm(); form.AddField("version", GameVersion); form.AddField("hash", securityCode); WWW www = new WWW(urlVersion, form); //this tells it to start the process by executing the function [WaitForRequest] StartCoroutine(WaitForRequest(www)); } catch (Exception) { //if there is a error change message to the following text errorMessage = "Could not connect to the server!"; } }
IEnumerator sendSkillSetApi() { string _uuid; if (PlayerPrefs.HasKey ("uuid")) { _uuid = PlayerPrefs.GetString ("uuid"); } else { yield break; } string url = ConfURL.HOST_NAME+ConfURL.PLAYER_SKILL_SUBMIT; WWWForm form = new WWWForm (); form.AddField ("UUID", _uuid); var skillList = ListObject.GetComponentsInChildren(typeof(SkillFieldController)); List<Skill> skillApi = new List<Skill>(); foreach(SkillFieldController skill in skillList){ skillApi.Add(skill.SkillData); Debug.Log( skill.SkillData.SkillName); } form.AddField ("json_api", LitJson.JsonMapper.ToJson(skillApi)); form.AddField ("player_id", playerStatus.ID); WWW www = new WWW(url, form); yield return www; SceneManager.LoadScene ("Home"); }
IEnumerator PostData() { Debug.Log("in get data"); string url = "192.168.33.11:3000/users/login"; WWWForm form = new WWWForm(); form.AddField("name", strId); form.AddField("room_no", strRo); WWW www = new WWW(url, form); yield return www; if (www.error == null) { Debug.Log(www.text); var textAsset =www; var jsonText = textAsset.text; var json = Json.Deserialize (jsonText) as Dictionary<string, object>; user_id= (long)json["user_id"]; Debug.Log (user_id); play_id= (long)json["play_id"]; Debug.Log (play_id); state= (string)json["state"]; Debug.Log (state); role= (string)json["role"]; Debug.Log (role); } }
private IEnumerator CreateAccountInternal (string username, string password, string email, UnityAction<bool> callback) { if (settings == null) { yield break; } WWWForm newForm = new WWWForm (); newForm.AddField ("name", username); newForm.AddField ("password", password); newForm.AddField ("email", email); WWW w = new WWW(settings.serverAddress + "/" + settings.createAccount, newForm); while (!w.isDone) { yield return new WaitForEndOfFrame(); } if (w.error != null) { Debug.LogError (w.error); } bool res = w.text.Trim ().Equals("true"); if (callback != null) { callback.Invoke (res); } AccountEventData eventData = new AccountEventData (); eventData.serverAdress = settings.serverAddress; User user = new User (username); user.password = password; eventData.user = user; eventData.result = res; Execute("OnCreateAccount",eventData); }
public void SaveGameState() { string url = "http://rangerdata.azurewebsites.net/"; //when the button is clicked //setup url to the ASP.NET webpage that is going to be called string customUrl = url + "SameGame/Create"; //setup a form WWWForm form = new WWWForm(); //Setup the paramaters //creates a random user form.AddField("GameName","Not Saved"); form.AddField("GameScore"," "); form.AddField("GameWaveNo"," "); form.AddField("username","LastRanger0"); //Call the server WWW www = new WWW(customUrl, form); StartCoroutine( WaitForRequest(www)); savepp.SavePosi (); // saveEp.SavePosi(); savePerkPos.SavePosi(); }
public IEnumerator MhSend2(string msg) { if (mh) yield break; if (msg != null) { if (isDebug) print(msg); mh = true; msg += " player:" + _Loader.playerName + " password:"******" deviceId:" + SystemInfo.deviceUniqueIdentifier + " version:" + setting.version; } WWWForm f = new WWWForm(); if (msg != null) f.AddField("msg", Convert.ToBase64String(Encoding.UTF8.GetBytes(msg))); f.AddField("id", SystemInfo.deviceUniqueIdentifier); f.AddField("version", setting.version); if(!guest) f.AddField("name", _Loader.playerName); //for (int i = 0; i < 10; i++) //{ var w = new WWW("https://tmrace.net/tm/scripts/stats2.php", f); print(w.url + Encoding.UTF8.GetString(f.data)); yield return w; //Debug.LogWarning(w.url + w.text); if (string.IsNullOrEmpty(w.error)) { if (w.text.StartsWith("1")) mh = true; //break; } //yield return new WaitForSeconds(60); //} }
// Use this for initialization IEnumerator Start() { //create webform to send to server WWWForm form = new WWWForm(); //add name and score form.AddField("user", player); form.AddField("score", score); //encrypt form.AddField("hash", Md5Sum(player + score + "TheSecretWord")); //connect and send WWW send = new WWW(url, form); //wait until complete yield return send; if (!string.IsNullOrEmpty(send.error)) { Debug.Log("highscore error " + send.error); } else { Debug.Log(send.text); } }
IEnumerator checkDetails() { var form = new WWWForm(); form.AddField("benutzername",GameObject.FindGameObjectWithTag("Username").GetComponent<InputField>().text); form.AddField("passwort", md5Sum(GameObject.FindGameObjectWithTag("Password").GetComponent<InputField>().text+"$K?1/S_@2%e#el!3>s#5BRo$a1+")); var connection = new WWW("http://www.1000sunny.de/games/eulmur/login.php", form); yield return connection; if (connection.error != null) Debug.Log("ouldn't connect to the server: " + connection.error); else if (connection.text.Equals("\n1")) { var getMoney = new WWW("http://www.1000sunny.de/games/eulmur/getmoney.php", form); yield return getMoney; var getLives = new WWW("http://www.1000sunny.de/games/eulmur/getlives.php", form); yield return getLives; var getClothes = new WWW("http://www.1000sunny.de/games/eulmur/getclothes.php", form); yield return getClothes; if (getMoney.error != null && getClothes.error != null && getLives.error != null) Debug.Log("Couldn't connect to the server: " + connection.error); else { PlayerData.LoadData(GameObject.FindGameObjectWithTag("Username").GetComponent<InputField>().text,getMoney.text,getLives.text,getClothes.text); SceneManager.LoadScene(2); } } else Debug.Log("falsches pw" + connection.text); }
string uploadLevelBlockUrl = "http://www.jun610.com/ourway/levelRecordings/levelBlockUpload.php"; //be sure to add a ? to your url #endregion Fields #region Methods public IEnumerator UploadLevelInfo(string levelID, string mapBlocks) { //CancelInvoke("DoRecord"); int lvVer = PlayerPrefs.GetInt("currentVersion"); string levelInfo = levelID + "_" + lvVer.ToString(); WWWForm form = new WWWForm(); form.AddField("action","saveLevel"); form.AddField("lvID", levelInfo); // form.AddField("content",mapBlocks); string s = mapBlocks; string[] itemSet = s.Split('/'); string blocks = ""; foreach(string i in itemSet){ if (i.Length <= 0 ){ break; } blocks += "|" + i; } form.AddField("blockID", blocks); // string objName = " "; // string index = " "; // string locString = " "; // // foreach(string i in itemSet){ // if (i.Length <= 0){ // break; // } // string[] subItemSet = i.Split('_'); // objName += subItemSet[0]; // index += subItemSet[1]; // string locxy = subItemSet[2]; // string[] xy = locxy.Split(','); // locString += xy[0] + "-" + xy[1]; // // } // // form.AddField("blockPos", locString); // form.AddField("blockType",objName); // form.AddField("blockID",index); //form.AddField("metrics", inMetrics.ToString() ); //this could be from Player Settings //form.AddField ("name", inID); WWW w = new WWW(uploadLevelBlockUrl,form); yield return w; if (w.error != null) { Debug.Log(w.error); } else { Debug.Log ("Successful Upload!"); Debug.Log (w.text + "\n\n" + form.ToString()); } }
public IEnumerator EmitFrame() { frameCounter += 1; bool shouldRender = this.renderImage && serverSideScreenshot; if (shouldRender) { // we should only read the screen buffer after rendering is complete yield return(new WaitForEndOfFrame()); } WWWForm form = new WWWForm(); MultiAgentMetadata multiMeta = new MultiAgentMetadata(); multiMeta.agents = new MetadataWrapper[this.agents.Count]; multiMeta.activeAgentId = this.activeAgentId; multiMeta.sequenceId = this.currentSequenceId; ThirdPartyCameraMetadata[] cameraMetadata = new ThirdPartyCameraMetadata[this.thirdPartyCameras.Count]; RenderTexture currentTexture = null; JavaScriptInterface jsInterface = null; if (shouldRender) { currentTexture = RenderTexture.active; for (int i = 0; i < this.thirdPartyCameras.Count; i++) { ThirdPartyCameraMetadata cMetadata = new ThirdPartyCameraMetadata(); Camera camera = thirdPartyCameras.ToArray()[i]; cMetadata.thirdPartyCameraId = i; cMetadata.position = camera.gameObject.transform.position; cMetadata.rotation = camera.gameObject.transform.eulerAngles; cameraMetadata[i] = cMetadata; ImageSynthesis imageSynthesis = camera.gameObject.GetComponentInChildren <ImageSynthesis> () as ImageSynthesis; addThirdPartyCameraImageForm(form, camera); addImageSynthesisImageForm(form, imageSynthesis, this.renderDepthImage, "_depth", "image_thirdParty_depth"); addImageSynthesisImageForm(form, imageSynthesis, this.renderNormalsImage, "_normals", "image_thirdParty_normals"); addImageSynthesisImageForm(form, imageSynthesis, this.renderObjectImage, "_id", "image_thirdParty_image_ids"); addImageSynthesisImageForm(form, imageSynthesis, this.renderClassImage, "_class", "image_thirdParty_classes"); addImageSynthesisImageForm(form, imageSynthesis, this.renderClassImage, "_flow", "image_thirdParty_flow");//XXX fix this in a bit } } for (int i = 0; i < this.agents.Count; i++) { BaseFPSAgentController agent = this.agents.ToArray() [i]; jsInterface = agent.GetComponent <JavaScriptInterface>(); MetadataWrapper metadata = agent.generateMetadataWrapper(); metadata.agentId = i; // we don't need to render the agent's camera for the first agent if (shouldRender) { addImageForm(form, agent); addImageSynthesisImageForm(form, agent.imageSynthesis, this.renderDepthImage, "_depth", "image_depth"); addImageSynthesisImageForm(form, agent.imageSynthesis, this.renderNormalsImage, "_normals", "image_normals"); addObjectImageForm(form, agent, ref metadata); addImageSynthesisImageForm(form, agent.imageSynthesis, this.renderClassImage, "_class", "image_classes"); addImageSynthesisImageForm(form, agent.imageSynthesis, this.renderFlowImage, "_flow", "image_flow"); metadata.thirdPartyCameras = cameraMetadata; } multiMeta.agents [i] = metadata; } if (shouldRender) { RenderTexture.active = currentTexture; } var serializedMetadata = Newtonsoft.Json.JsonConvert.SerializeObject(multiMeta); #if UNITY_WEBGL // JavaScriptInterface jsI = FindObjectOfType<JavaScriptInterface>(); // jsInterface.SendAction(new ServerAction(){action = "Test"}); if (jsInterface != null) { jsInterface.SendActionMetadata(serializedMetadata); } #endif //form.AddField("metadata", JsonUtility.ToJson(multiMeta)); form.AddField("metadata", serializedMetadata); form.AddField("token", robosimsClientToken); #if !UNITY_WEBGL if (synchronousHttp) { if (this.sock == null) { // Debug.Log("connecting to host: " + robosimsHost); IPAddress host = IPAddress.Parse(robosimsHost); IPEndPoint hostep = new IPEndPoint(host, robosimsPort); this.sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { this.sock.Connect(hostep); } catch (SocketException e) { Debug.Log("Socket exception: " + e.ToString()); } } if (this.sock != null && this.sock.Connected) { byte[] rawData = form.data; string request = "POST /train HTTP/1.1\r\n" + "Content-Length: " + rawData.Length.ToString() + "\r\n"; foreach (KeyValuePair <string, string> entry in form.headers) { request += entry.Key + ": " + entry.Value + "\r\n"; } request += "\r\n"; int sent = this.sock.Send(Encoding.ASCII.GetBytes(request)); sent = this.sock.Send(rawData); // waiting for a frame here keeps the Unity window in sync visually // its not strictly necessary, but allows the interact() command to work properly // and does not reduce the overall FPS yield return(new WaitForEndOfFrame()); byte[] headerBuffer = new byte[1024]; int bytesReceived = 0; byte[] bodyBuffer = null; int bodyBytesReceived = 0; int contentLength = 0; // read header while (true) { int received = this.sock.Receive(headerBuffer, bytesReceived, headerBuffer.Length - bytesReceived, SocketFlags.None); if (received == 0) { Debug.LogError("0 bytes received attempting to read header - connection closed"); break; } bytesReceived += received;; string headerMsg = Encoding.ASCII.GetString(headerBuffer, 0, bytesReceived); int offset = headerMsg.IndexOf("\r\n\r\n"); if (offset > 0) { contentLength = parseContentLength(headerMsg.Substring(0, offset)); bodyBuffer = new byte[contentLength]; bodyBytesReceived = bytesReceived - (offset + 4); Array.Copy(headerBuffer, offset + 4, bodyBuffer, 0, bodyBytesReceived); break; } } // read body while (bodyBytesReceived < contentLength) { // check for 0 bytes received int received = this.sock.Receive(bodyBuffer, bodyBytesReceived, bodyBuffer.Length - bodyBytesReceived, SocketFlags.None); if (received == 0) { Debug.LogError("0 bytes received attempting to read body - connection closed"); break; } bodyBytesReceived += received; //Debug.Log("total bytes received: " + bodyBytesReceived); } string msg = Encoding.ASCII.GetString(bodyBuffer, 0, bodyBytesReceived); ProcessControlCommand(msg); } } else { using (var www = UnityWebRequest.Post("http://" + robosimsHost + ":" + robosimsPort + "/train", form)) { yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.Log("Error: " + www.error); yield break; } ProcessControlCommand(www.downloadHandler.text); } } #endif }
IEnumerator SendSat(string recipientAddress, int amountSat, int feeSat) { Log("Requesting transaction outputs for address " + m_address.ToString()); SetSendPanelInteractable(false); //INPUT: money coming from an address //OUTPUT: money going to an address //Request all unspent transactions related to this address //https://live.blockcypher.com/btc/address/<address> shows the same but nicely WWW wwwTxo = new WWW("https://blockchain.info/unspent?active=" + m_address.ToString() + ""); yield return(wwwTxo); if (wwwTxo.error != null) { Log("Cannot get utxo from \"" + wwwTxo.url + "\"\nError: " + wwwTxo.error); SetSendPanelInteractable(true); } else { // { // "unspent_outputs": [ // { // "tx_hash": "aed0a61f789e80975425685ef65ba0a0e388db0c001dfd9e548e896fe39c1067", // "tx_hash_big_endian": "67109ce36f898e549efd1d000cdb88e3a0a05bf65e68255497809e781fa6d0ae", // "tx_output_n": 0, // "script": "76a914717ee27eca5ed0bd30fde351a19439ed96bdcb3f88ac", // "value": 2176, // "value_hex": "0880", // "confirmations": 0, // "tx_index": 461965676 // } // ] // } JSONObject utxos = new JSONObject(wwwTxo.text); //Get all unspent outputs using my address List <Coin> unspentCoins = new List <Coin>(); for (int i = 0; i < utxos["unspent_outputs"].Count; i++) { string txHash = utxos["unspent_outputs"][i]["tx_hash_big_endian"].str; uint outputIndex = (uint)utxos["unspent_outputs"][i]["tx_output_n"].n; int valueUnspent = (int)utxos["unspent_outputs"][i]["value"].n; Log(valueUnspent + " unspent!"); unspentCoins.Add(new Coin( new uint256(txHash), //Hash of the transaction this output is comming from outputIndex, //Index of the transaction output within the transaction Money.Satoshis(valueUnspent), //Amount of money this output has m_address.ScriptPubKey)); //Script to solve to spend this output } //+info about how to use TransactionBuilder can be found here //https://csharp.hotexamples.com/examples/NBitcoin/TransactionBuilder/-/php-transactionbuilder-class-examples.html TransactionBuilder txBuilder = Network.Main.CreateTransactionBuilder(); txBuilder.AddKeys(WalletMnemonic.DeriveExtKey().PrivateKey); txBuilder.AddCoins(unspentCoins); txBuilder.Send(BitcoinAddress.Create(recipientAddress, Network.Main), Money.Satoshis(amountSat)); txBuilder.SendFees(Money.Satoshis(feeSat)); txBuilder.SetChange(m_address); Transaction tx = txBuilder.BuildTransaction(true); Log(tx.ToHex().ToString()); //Submit raw transaction to a bitcoin node //In this case we use blockchain.info API WWWForm form = new WWWForm(); form.AddField("tx", tx.ToHex()); WWW wwwRawTx = new WWW("https://blockchain.info/pushtx", form); yield return(wwwRawTx); if (wwwRawTx.error != null) { Log("Error submitting raw transaction " + wwwRawTx.error, true); } else { Log(wwwTxo.text); Log("Transaction sent!"); yield return(new WaitForSeconds(3f)); Application.OpenURL("https://www.blockchain.com/btc/address/" + m_address); yield return(StartCoroutine(RefreshBalance())); } } SetSendPanelInteractable(true); }
IEnumerator login_action() { //iTween.MoveTo(loginpage, iTween.Hash("position", loginpage_pos, "easeType", iTween.EaseType.linear, "isLocal", true, //"time", 0.5f)); iTween.ScaleTo(UpdatedLoginPage, Vector3.zero, 0.5f); yield return(new WaitForSeconds(0.6f)); UpdatedLoginPage.SetActive(false); var username = username_input.text; var password = password_input.text; var encryptedpassword = asealgorithm.getEncryptedString(password); if (username != "" && password != "") { loadinganim.SetActive(true); username_input.text = ""; password_input.text = ""; ////-------offline test------------------------// //if (username == "shubham" && password == "12345") //{ // username_input.text = ""; // password_input.text = ""; // username_input.GetComponent<InputField>().enabled = false; // password_input.GetComponent<InputField>().enabled = false; // loginbutton.GetComponent<Button>().enabled = false; // homebutton.SetActive(false); // string msg = "Login Successfully!"; // StartCoroutine(Messagedisplay(msg)); // yield return new WaitForSeconds(3.5f); // firstscreen.SetActive(false); // loginpage.SetActive(false); // StartCoroutine(scenechanges(this.gameObject, toplayer_sprite)); // yield return new WaitForSeconds(1.2f); // string profile_data = PlayerPrefs.GetString("profile_done"); // if (profile_data != "done") // { // superhero.SetActive(true); // } // else // { // toplayer.SetActive(true); // } // // StartCoroutine(Enablepage(profilesetup_page, loginpage, 4f)); //} //else //{ // username_input.text = ""; // password_input.text = ""; // string msg = "Login Failed"; // homebutton.SetActive(true); // StartCoroutine(Messagedisplay(msg)); //} //----------------------api integration -------------// string loginlink = Mainurl + login_API; Debug.Log(loginlink); WWWForm loginForm = new WWWForm(); loginForm.AddField("IMEI", ""); loginForm.AddField("USERID", username); loginForm.AddField("PASSWORD", encryptedpassword); loginForm.AddField("OS", ""); loginForm.AddField("Network", ""); loginForm.AddField("OSVersion", ""); loginForm.AddField("Details", ""); loginForm.AddField("REURL", ""); WWW loginurl = new WWW(loginlink, loginForm); yield return(loginurl); if (loginurl.text != null) { Debug.Log(loginurl.text); login_json = JsonMapper.ToObject(loginurl.text); string status = login_json["AuthStatus"].ToString(); int UID = int.Parse(login_json["IDUSER"].ToString()); int OID = int.Parse(login_json["OID"].ToString()); int game_id = int.Parse(login_json["id_org_game_unit"].ToString()); PlayerPrefs.SetInt("game_id", game_id); if (status.ToLower() == "success") { if (UID == PlayerPrefs.GetInt("UID")) { PlayerPrefs.SetInt("UID", UID); PlayerPrefs.SetInt("OID", OID); PlayerPrefs.SetInt("game_id", game_id); if (login_json["FIRST_NAME"].ToString() != null) { PlayerPrefs.SetString("username", login_json["FIRST_NAME"].ToString()); } if (login_json["UserGrade"] != null) { PlayerPrefs.SetString("User_grade", login_json["UserGrade"].ToString()); } if (login_json["id_school"] != null) { PlayerPrefs.SetInt("id_school", int.Parse(login_json["id_school"].ToString())); } PlayerPrefs.SetInt("characterType", int.Parse(login_json["avatar_type"].ToString())); if (login_json["avatar_type"].ToString() != "0") { PlayerPrefs.SetString("profile_done", "done"); } } else { PlayerPrefs.SetInt("UID", UID); PlayerPrefs.SetInt("OID", OID); PlayerPrefs.SetInt("game_id", game_id); if (login_json["FIRST_NAME"] != null) { PlayerPrefs.SetString("username", login_json["FIRST_NAME"].ToString()); } if (login_json["UserGrade"] != null) { PlayerPrefs.SetString("User_grade", login_json["UserGrade"].ToString()); } if (login_json["id_school"] != null) { PlayerPrefs.SetInt("id_school", int.Parse(login_json["id_school"].ToString())); } PlayerPrefs.SetInt("characterType", int.Parse(login_json["avatar_type"].ToString())); if (login_json["avatar_type"].ToString() != "0") { PlayerPrefs.SetString("profile_done", "done"); } else { PlayerPrefs.DeleteKey("profile_done"); PlayerPrefs.DeleteKey("username"); PlayerPrefs.DeleteKey("User_grade"); PlayerPrefs.DeleteKey("characterType"); } } //===============================================================// settingpanelbtn.gameObject.SetActive(true); username_leftdashboard.text = PlayerPrefs.GetString("username"); username_input.GetComponent <InputField>().enabled = true; password_input.GetComponent <InputField>().enabled = true; loginbutton.GetComponent <Button>().enabled = true; homebutton.SetActive(false); loadinganim.SetActive(false); string msg = "Logged In Successfully!"; StartCoroutine(Messagedisplay(msg)); yield return(new WaitForSeconds(3.5f)); // firstscreen.SetActive(false); loginpage.SetActive(false); if (remeberme.isOn == true) { PlayerPrefs.SetString("logged", "true"); } remeberme.isOn = false; StartCoroutine(scenechanges(HomepageObject, toplayer_sprite)); yield return(new WaitForSeconds(1.2f)); superhero.SetActive(true); } else { username_input.GetComponent <InputField>().enabled = true; password_input.GetComponent <InputField>().enabled = true; loginbutton.GetComponent <Button>().enabled = true; loadinganim.SetActive(false); string msg = "Login In Failed!!"; StartCoroutine(Messagedisplay(msg)); yield return(new WaitForSeconds(3.5f)); loginpage.SetActive(true); } } } }
internal Coroutine CreateMatch(CreateMatchRequest req, DataResponseDelegate <MatchInfo> callback) { if (callback == null) { Debug.Log("callback supplied is null, aborting CreateMatch Request."); return(null); } Uri uri = new Uri(baseUri, "/json/reply/CreateMatchRequest"); Debug.Log("MatchMakingClient Create :" + uri); var data = new WWWForm(); data.AddField("version", UnityEngine.Networking.Match.Request.currentVersion); data.AddField("projectId", Application.cloudProjectId); data.AddField("sourceId", Utility.GetSourceID().ToString()); data.AddField("accessTokenString", 0); // Set the access token to 0 for any new match request data.AddField("domain", req.domain); data.AddField("name", req.name); data.AddField("size", req.size.ToString()); data.AddField("advertise", req.advertise.ToString()); data.AddField("password", req.password); data.AddField("publicAddress", req.publicAddress); data.AddField("privateAddress", req.privateAddress); data.AddField("eloScore", req.eloScore.ToString()); data.headers["Accept"] = "application/json"; var client = UnityWebRequest.Post(uri.ToString(), data); return(StartCoroutine(ProcessMatchResponse <CreateMatchResponse, DataResponseDelegate <MatchInfo> >(client, OnMatchCreate, callback))); }
IEnumerator senditem() { //서버에서 케릭터의 아이템 리스트를 받아온다 string id = PlayerPrefs.GetString("id"); Debug.Log("id" + id); string pw = PlayerPrefs.GetString("pw"); Debug.Log("pw" + pw); int userindex = PlayerPrefs.GetInt("userindex"); //스테이지가 3인데 clear변수가 1이면 int chapter = GameObject.Find("singlescenestart_cs").GetComponent <Singlescenestart>().chapter; int chapterclear = GameObject.Find("clearcheck").GetComponent <clearcheck>().chapterclear; //현재 챕터 +1; int maxchapter = chapter; if (chapterclear == 1) { //보내도 됨 maxchapter = chapter + 1; } WWWForm w = new WWWForm(); w.AddField("select", "submit"); w.AddField("id", id); w.AddField("pw", pw); w.AddField("userindex", userindex); w.AddField("gold", gold); w.AddField("maxchapter", maxchapter); w.AddField("itemjson", itemToJason); Debug.Log("2 , form 구성 아이디 비밀번호 로그인방식"); Debug.Log("3 , register.php에 form 전달"); UnityWebRequest www = UnityWebRequest.Post("http://49.247.131.90/itemsend.php", w); Debug.Log("4 , 통신 반환값 전달"); yield return(www.SendWebRequest()); //서버 연결 실패 if (www.isNetworkError || www.isHttpError) { Debug.Log("5, 네트워크 통신 error: " + www.error); } else //서버 연결 성공 { result = www.downloadHandler.text; Debug.Log("5, !!!!!!!!!!!!!!!!!네트워크 통신 성공 result: " + result); clickcount = 0; SceneManager.LoadScene("mainscene"); } }
private IEnumerator Start() { DontDestroyOnLoad(gameObject); WWWForm form = new WWWForm(); string from = "editor"; #if UNITY_ANDROID from = "android"; #elif UNITY_IOS from = "ios"; #endif form.AddField("requestfrom", from); if (m_formData != null) { foreach (string key in m_formData.Keys) { form.AddField(key, m_formData[key].ToString()); } } if ((url.IndexOf("facebook") > 0) == false) { Dictionary <string, string> headers = form.headers; string user = "******"; string pass = "******"; headers["Authorization"] = "Basic " + System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(user + ":" + pass)); byte[] rawData = form.data; //m_www = isPost ? new WWW(url, rawData, headers) : new WWW(url); m_www = new WWW(url, rawData, headers); } else { m_www = new WWW(url); } yield return(m_www); if (m_callback != null) { m_callback(m_www); } if (m_image != null) { Texture2D tex = MaskTexture2D(m_www.texture); MyDebug.Log("Load image with " + tex.width); m_image.sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), Vector2.one * 0.5f); } s_all.Remove(this); Destroy(gameObject); }
private IEnumerator ProcessRequestQueue() { // yield AFTER we increment the connection count, so the Send() function can return immediately _activeConnections += 1; #if UNITY_EDITOR if (!UnityEditorInternal.InternalEditorUtility.inBatchMode) { yield return(null); } #else yield return(null); #endif while (_requests.Count > 0) { Request req = _requests.Dequeue(); if (req.Cancel) { continue; } string url = URL; if (!string.IsNullOrEmpty(req.Function)) { url += req.Function; } StringBuilder args = null; foreach (var kp in req.Parameters) { var key = kp.Key; var value = kp.Value; if (value is string) { value = WWW.EscapeURL((string)value); // escape the value } else if (value is byte[]) { value = Convert.ToBase64String((byte[])value); // convert any byte data into base64 string } else if (value is Int32 || value is Int64 || value is UInt32 || value is UInt64 || value is float || value is bool) { value = value.ToString(); } else if (value != null) { Log.Warning("RESTConnector.ProcessRequestQueue()", "Unsupported parameter value type {0}", value.GetType().Name); } else { Log.Error("RESTConnector.ProcessRequestQueue()", "Parameter {0} value is null", key); } if (args == null) { args = new StringBuilder(); } else { args.Append("&"); // append separator } args.Append(key + "=" + value); // append key=value } if (args != null && args.Length > 0) { url += "?" + args.ToString(); } AddHeaders(req.Headers); Response resp = new Response(); DateTime startTime = DateTime.Now; if (!req.Delete && !req.Post) { WWW www = null; if (req.Forms != null) { if (req.Send != null) { Log.Warning("RESTConnector", "Do not use both Send & Form fields in a Request object."); } WWWForm form = new WWWForm(); try { foreach (var formData in req.Forms) { if (formData.Value.IsBinary) { form.AddBinaryData(formData.Key, formData.Value.Contents, formData.Value.FileName, formData.Value.MimeType); } else if (formData.Value.BoxedObject is string) { form.AddField(formData.Key, (string)formData.Value.BoxedObject); } else if (formData.Value.BoxedObject is int) { form.AddField(formData.Key, (int)formData.Value.BoxedObject); } else if (formData.Value.BoxedObject != null) { Log.Warning("RESTConnector.ProcessRequestQueue()", "Unsupported form field type {0}", formData.Value.BoxedObject.GetType().ToString()); } } foreach (var headerData in form.headers) { req.Headers[headerData.Key] = headerData.Value; } } catch (Exception e) { Log.Error("RESTConnector.ProcessRequestQueue()", "Exception when initializing WWWForm: {0}", e.ToString()); } www = new WWW(url, form.data, req.Headers); } else if (req.Send == null) { www = new WWW(url, null, req.Headers); } else { www = new WWW(url, req.Send, req.Headers); } #if ENABLE_DEBUGGING Log.Debug("RESTConnector", "URL: {0}", url); #endif // wait for the request to complete. float timeout = Mathf.Max(Constants.Config.Timeout, req.Timeout); while (!www.isDone) { if (req.Cancel) { break; } if ((DateTime.Now - startTime).TotalSeconds > timeout) { break; } if (req.OnUploadProgress != null) { req.OnUploadProgress(www.uploadProgress); } if (req.OnDownloadProgress != null) { req.OnDownloadProgress(www.progress); } #if UNITY_EDITOR if (!UnityEditorInternal.InternalEditorUtility.inBatchMode) { yield return(null); } #else yield return(null); #endif } if (req.Cancel) { continue; } bool bError = false; Error error = null; if (!string.IsNullOrEmpty(www.error)) { long nErrorCode = -1; int nSeperator = www.error.IndexOf(' '); if (nSeperator > 0 && long.TryParse(www.error.Substring(0, nSeperator).Trim(), out nErrorCode)) { switch (nErrorCode) { case HTTP_STATUS_OK: case HTTP_STATUS_CREATED: case HTTP_STATUS_ACCEPTED: bError = false; break; default: bError = true; break; } } else { bError = true; } error = new Error() { URL = url, ErrorCode = resp.HttpResponseCode = nErrorCode, ErrorMessage = www.error, Response = www.text, ResponseHeaders = www.responseHeaders }; if (bError) { Log.Error("RESTConnector.ProcessRequestQueue()", "URL: {0}, ErrorCode: {1}, Error: {2}, Response: {3}", url, nErrorCode, www.error, string.IsNullOrEmpty(www.text) ? "" : www.text); } else { Log.Warning("RESTConnector.ProcessRequestQueue()", "URL: {0}, ErrorCode: {1}, Error: {2}, Response: {3}", url, nErrorCode, www.error, string.IsNullOrEmpty(www.text) ? "" : www.text); } } if (!www.isDone) { Log.Error("RESTConnector.ProcessRequestQueue()", "Request timed out for URL: {0}", url); bError = true; } /*if (!bError && (www.bytes == null || www.bytes.Length == 0)) * { * Log.Warning("RESTConnector.ProcessRequestQueue()", "No data recevied for URL: {0}", url); * bError = true; * }*/ // generate the Response object now.. if (!bError) { resp.Success = true; resp.Data = www.bytes; resp.HttpResponseCode = GetResponseCode(www); } else { resp.Success = false; resp.Error = error; } resp.Headers = www.responseHeaders; resp.ElapsedTime = (float)(DateTime.Now - startTime).TotalSeconds; // if the response is over a threshold, then log with status instead of debug if (resp.ElapsedTime > LogResponseTime) { Log.Warning("RESTConnector.ProcessRequestQueue()", "Request {0} completed in {1} seconds.", url, resp.ElapsedTime); } if (req.OnResponse != null) { req.OnResponse(req, resp); } www.Dispose(); } else if (req.Post) { float timeout = Mathf.Max(Constants.Config.Timeout, req.Timeout); PostRequest postReq = new PostRequest(); Runnable.Run(postReq.Send(url, req.Headers)); while (!postReq.IsComplete) { if (req.Cancel) { break; } if ((DateTime.Now - startTime).TotalSeconds > timeout) { break; } yield return(null); } if (req.Cancel) { continue; } resp.Success = postReq.Success; resp.Data = postReq.Data; resp.Error = postReq.Error; resp.HttpResponseCode = postReq.HttpResponseCode; resp.ElapsedTime = (float)(DateTime.Now - startTime).TotalSeconds; resp.Headers = postReq.ResponseHeaders; if (req.OnResponse != null) { req.OnResponse(req, resp); } } else { #if ENABLE_DEBUGGING Log.Debug("RESTConnector.ProcessRequestQueue90", "Delete Request URL: {0}", url); #endif float timeout = Mathf.Max(Constants.Config.Timeout, req.Timeout); DeleteRequest deleteReq = new DeleteRequest(); Runnable.Run(deleteReq.Send(url, req.Headers)); while (!deleteReq.IsComplete) { if (req.Cancel) { break; } if ((DateTime.Now - startTime).TotalSeconds > timeout) { break; } yield return(null); } if (req.Cancel) { continue; } resp.Success = deleteReq.Success; resp.Data = deleteReq.Data; resp.Error = deleteReq.Error; resp.HttpResponseCode = deleteReq.HttpResponseCode; resp.ElapsedTime = (float)(DateTime.Now - startTime).TotalSeconds; resp.Headers = deleteReq.ResponseHeaders; if (req.OnResponse != null) { req.OnResponse(req, resp); } } } // reduce the connection count before we exit.. _activeConnections -= 1; yield break; }
IEnumerator DispararPlayer(Coordenadas coordenadas) { string json = JsonUtility.ToJson(coordenadas); string jsondata = ""; WWWForm form = new WWWForm(); form.AddField("json", json); using (UnityWebRequest webRequest = UnityWebRequest.Post(url + "dispararplayer", form)) { yield return(webRequest.SendWebRequest()); if (webRequest.isNetworkError || webRequest.isHttpError) { Debug.Log(webRequest.error); Debug.Log("Ha pasado algo"); Debug.Log(webRequest.downloadHandler.text); } else { Debug.Log("Form upload complete!"); jsondata = webRequest.downloadHandler.text; } } // Procesar el JSON y obtener la palabra cifrada if (jsondata != "") { Debug.Log(jsondata); Coordenadas aw = Coordenadas.CreateFromJSON(jsondata); if (aw.tipoBarco != "A") { // aw contiene los datos de .tipoBarco que son PIA MIA GIA o A (este ultimo quiere decir que no has dado a ninguno (AGUA)) // si tipoBarco devuelve "A" quiere decir que no has acertado a ningun barco Debug.Log("HE DADOD HA: " + aw.tipoBarco); // .destruido te dira "SI" si has destruido por completo ese tipo de barco o "NO" si no lo has destruido por completo Debug.Log("SI LO HE DESTRUIDO: " + aw.destruido); directoX = placementDX(changeLetterToInt(PlayerPrefs.GetString("ApuntaX"))); directoY = placementDY(int.Parse(PlayerPrefs.GetString("ApuntaY"))); manager.GetComponent <Manager>().pegadoNum = manager.GetComponent <Manager>().pegadoNum - 1; if (contador == 0) { tick1.GetComponent <RectTransform>().anchoredPosition = new Vector2(directoX, directoY); contador++; } else if (contador == 1) { tick2.GetComponent <RectTransform>().anchoredPosition = new Vector2(directoX, directoY); contador++; } else if (contador == 2) { tick3.GetComponent <RectTransform>().anchoredPosition = new Vector2(directoX, directoY); contador++; } else if (contador == 3) { tick4.GetComponent <RectTransform>().anchoredPosition = new Vector2(directoX, directoY); contador++; } else if (contador == 4) { tick5.GetComponent <RectTransform>().anchoredPosition = new Vector2(directoX, directoY); contador++; } else if (contador == 5) { tick6.GetComponent <RectTransform>().anchoredPosition = new Vector2(directoX, directoY); contador++; } else if (contador == 6) { tick7.GetComponent <RectTransform>().anchoredPosition = new Vector2(directoX, directoY); contador++; } else if (contador == 7) { tick8.GetComponent <RectTransform>().anchoredPosition = new Vector2(directoX, directoY); contador++; } } else { Debug.Log("AGUA"); } } else { Debug.Log("asgf " + jsondata); } }
/// <summary> /// 上传文件 /// </summary> /// <param name="fileParams">文件参数.</param> /// <param name="parameters">请求参数.</param> /// <param name="resultHandler">返回回调.</param> /// <param name="faultHandler">失败回调.</param> /// <param name="progressHandler">进度回调</param> public void upload( Dictionary <string, HTTPFile> fileParams, Dictionary <string, string> parameters, LuaFunction resultHandler, LuaFunction faultHandler, LuaFunction progressHandler) { _resultHandler = resultHandler; _faultHandler = faultHandler; _uploadProgressHandler = progressHandler; #if UNITY_ANDROID && !UNITY_EDITOR string appPath = luascriptcore.modules.foundation.Path.app(); AndroidJavaObject currentActivity = UNIEnv.getCurrentActivity(); AndroidJavaObject assetManager = currentActivity.Call <AndroidJavaObject> ("getAssets", new object[0]); #endif WWWForm form = new WWWForm(); if (fileParams != null) { foreach (KeyValuePair <string, HTTPFile> kv in fileParams) { HTTPFile file = kv.Value; string path = file.path; byte[] fileData = null; #if UNITY_ANDROID && !UNITY_EDITOR if (path.StartsWith(appPath) || !path.StartsWith("/")) { //应用包内文件 if (path.StartsWith(appPath)) { path = path.Substring(appPath.Length + 1); } AndroidJavaObject inputStream = assetManager.Call <AndroidJavaObject> ("open", path); using (MemoryStream ms = new MemoryStream()) { try { IntPtr buffer = AndroidJNI.NewByteArray(1024); jvalue[] args = new jvalue[1]; args [0].l = buffer; IntPtr readMethodId = AndroidJNIHelper.GetMethodID(inputStream.GetRawClass(), "read", "([B)I"); int hasRead = 0; while ((hasRead = AndroidJNI.CallIntMethod(inputStream.GetRawObject(), readMethodId, args)) != -1) { byte[] byteArray = AndroidJNIHelper.ConvertFromJNIArray <byte[]> (buffer); ms.Write(byteArray, 0, hasRead); } fileData = new byte[ms.Length]; ms.Read(fileData, 0, (int)ms.Length); } finally { ms.Close(); } } } else { #endif FileStream fs = new FileStream(path, FileMode.Open); try { fileData = new byte[fs.Length]; fs.Read(fileData, 0, (int)fs.Length); } finally { fs.Close(); } #if UNITY_ANDROID && !UNITY_EDITOR } #endif if (fileData != null) { form.AddBinaryData(kv.Key, fileData, System.IO.Path.GetFileName(file.path), file.mimeType); } } } if (parameters != null) { foreach (KeyValuePair <string, string> kv in parameters) { form.AddField(kv.Key, kv.Value); } } _request = UnityWebRequest.Post(url, form); if (_request != null) { fillHeaders(); sendRequest(); } }
//获取该target下的所有用户及视频信息 //POST /videos/cloud/targetId/{targetId}/memberCode/{memberCode} 2018-01-22-用户查看云识别时光轴 IEnumerator LoadImageTarget(ImageTarget target, System.Action <ImageTarget, VideoTargetDate> handle) { /*自动获取手机的信息 * System.Collections.Generic.Dictionary<string, string> headers = new System.Collections.Generic.Dictionary<string, string>(); * * headers.Add("Content-Type", "application/json"); * * * JsonData data = new JsonData(); * data["phone"] = "13816848999"; * data["targetId"] = "920df90c-dbb4-41bf-ab70-b2bc14c189c1"; * data["token"] = ""; * byte[] bs = System.Text.UTF8Encoding.UTF8.GetBytes(data.ToJson()); * * //WWW www = new WWW("http://106.14.60.213:8080/business/AR/cloud", bs, headers); * * //headers.Add("token", App.MgrConfig._token); */ WWWForm wwwForm = new WWWForm(); wwwForm.AddField("phone", App.MgrConfig._phone); wwwForm.AddField("targetId", target.Uid); wwwForm.AddField("token", ""); byte[] rawData = wwwForm.data; WWW www = new WWW(App.MgrConfig._Server + "AR/cloud", wwwForm); /* * Dictionary<string, string> headers = new Dictionary<string, string>(); * headers.Add("Content-Type", "application/json"); * JsonData jsonData = new JsonData(); * jsonData["phone"] = App.MgrConfig._phone; * jsonData["targetId"] = target.Uid; * Debug.Log(jsonData.ToJson()); * //byte[] bs = System.Text.UTF8Encoding.UTF8.GetBytes(data.ToJson()); * byte[] bs = System.Text.Encoding.UTF8.GetBytes(jsonData.ToJson()); * * WWW www = new WWW(App.MgrConfig._Server +"AR/cloud",bs,headers); */ yield return(www); string m_info = string.Empty; if (www.error != null) { m_info = www.error; yield return(null); } if (www.isDone && www.error == null) { m_info = www.text.ToString(); yield return(m_info); Debug.Log(m_info); JsonData jd = JsonMapper.ToObject(m_info); string id = jd["data"]["id"].ToString(); jd = jd["data"]["timeLineVideoList"]; if (jd == null) { Destroy(GameObject.Find(target.Uid)); yield break; } //Debug.Log (jd.ToString ()); byte[] bytes = Convert.FromBase64String(target.MetaData); string s = System.Text.Encoding.GetEncoding("utf-8").GetString(bytes); VideoTargetDate data = new VideoTargetDate(target.Uid, s, id, ""); for (int i = 0; i < jd.Count; i++) { VideoTargetCell cell = new VideoTargetCell( jd [i] ["createDate"].ToString(), jd [i] ["user"]["nickName"].ToString(), jd [i] ["timeVideoSrc"].ToString(), jd [i] ["user"]["userLogo"].ToString(), jd [i] ["user"]["id"].ToString(), jd [i] ["user"]["isFriend"].ValueAsBoolean(), jd[i]["isVertical"].ToString()); data.videoList.Add(cell); } handle(target, data); } }
public IEnumerator TryAuthenticate() { bool isAuthenticated = false; progressText.text = "Authenticating"; string customUrl = url + "Login.aspx"; WWWForm form = new WWWForm(); passwordHash = Sha1Sum2(password); form.AddField("username", username); form.AddField("password", passwordHash); using (UnityWebRequest www = UnityWebRequest.Post(customUrl, form)) { www.SetRequestHeader("Content-Type", "application/x-www-form-urlencoded"); yield return(www.SendWebRequest()); if (www.isNetworkError) { StopCoroutine(LoadingBar()); loadingBar.fillAmount = 0f; progressText.text = www.error; loginButton.SetActive(true); } else { StringBuilder sb = new StringBuilder(); foreach (System.Collections.Generic.KeyValuePair <string, string> dict in www.GetResponseHeaders()) { sb.Append(dict.Key).Append(": \t[").Append(dict.Value).Append("]\n"); } if (www.downloadHandler.text == "True") { // StopCoroutine(LoadingBar()); if (loadingBar.fillAmount < .25f) { loadingBar.fillAmount = 0.25f; } progressText.text = "Authentication Successful"; playerData.playerName = username; yield return(new WaitForSeconds(.1f)); progressText.text = "Loading Player Data"; dataHandler.CreateLocalUser(username); if (!dataHandler.LoadData()) { progressText.text = "Failed To Load Player Data"; StopCoroutine("LoadingBar"); loadingBar.fillAmount = 0f; yield return(new WaitForSeconds(2f)); SceneManager.LoadScene(0); } else { isAuthenticated = true; } if (loadingBar.fillAmount < .5f && isAuthenticated) { loadingBar.fillAmount = .5f; } if (PlayerPrefs.GetInt("RememberPassword") == 1) { PlayerPrefs.SetString("Password", password); } else { PlayerPrefs.SetString("Password", ""); } // dataHandler.SaveData(); // dataHandler.SaveData(); if (isAuthenticated) { LaunchGame(); } } else { StopCoroutine("LoadingBar"); loadingBar.fillAmount = 0f; progressLabel.SetActive(true); progressText.text = "Invalid Password"; loginButton.SetActive(true); } } } }
IEnumerator LoginUser() { WWWForm form = new WWWForm(); form.AddField("name", nameField.text); form.AddField("password", passwordField.text); UnityWebRequest www = UnityWebRequest.Post($"http://{NetworkConstants.IpAddress}/sqlconnect/login.php", form); yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); InfoText.text = www.error; } else { string[] serverData = www.downloadHandler.text.Split('\t'); if (serverData[0] == "0") { Debug.Log("User logged in"); InfoText.text = "User logged in"; DBManager.username = nameField.text; DBManager.achievements = new HashSet <string>(serverData[1].Split(',').ToList()); DBManager.face_recognition_image_location = serverData[2]; Debug.Log(serverData[3]); DBManager.role_id = System.Convert.ToInt32(serverData[3]); DBManager.id = System.Convert.ToInt32(serverData[4]); // TODO: microlesson setup DBManager.microLesson.LessonName = "virtual_reality"; //TODO: add presentation_ppt_content to DB DBManager.microLesson.presentation_ppt_content = $"http://{NetworkConstants.IpAddress}/presentations/{DBManager.microLesson.LessonName}/"; // C:\MAMP\htdocs\presentations\acauser123\virtual_reality Debug.Log(@"C:\MAMP\htdocs\Python\face_recognize_webcam.py" + @" ..\" + DBManager.face_recognition_image_location); Debug.Log(DBManager.microLesson.presentation_ppt_content); //Without face detection -> GoToVirtualRoom(); MultiplayerMenu sn = multiPlayerMenu.GetComponent <MultiplayerMenu>(); if (DBManager.role_id == 1) { sn.Host(); } else if (DBManager.role_id == 2) { sn.Connect(); } // load ip adress form = new WWWForm(); form.AddField("user_id", DBManager.id); www = UnityWebRequest.Post($"http://{NetworkConstants.IpAddress}/sqlconnect/getIpAddress.php", form); yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); InfoText.text = www.error; } else { Debug.Log("IP address " + www.downloadHandler.text); // TODO: ip address for networking, NetworkConstants.IpAddress is db address //yield return new WaitForSeconds(1); //Wait //FaceRecognitionManager.Start(); GoToVirtualRoom(); } } else { Debug.Log("User logged in failed. Error #" + www.downloadHandler.text); InfoText.text = "User logged in failed. Error #" + www.downloadHandler.text; } } }
IEnumerator Login(string userID, string pletformID = "", LoginType loginType = LoginType.GuestLogin) { Debug.Log("로그인 시작"); loginPanel.SetActive(false); //로그인 시 유저 데이터 구성부분 WWWForm form = new WWWForm(); form.AddField("userID", userID, System.Text.Encoding.UTF8); //테스트 아이디로 로그인한다. string googleID = ""; if (PlayerPrefs.HasKey("google")) { googleID = PlayerPrefs.GetString("google"); } else { if (loginType == LoginType.GoogleLogin) { googleID = pletformID; } } string facebookID = ""; if (PlayerPrefs.HasKey("facebook")) { facebookID = PlayerPrefs.GetString("facebook"); } else { if (loginType == LoginType.FacebookLogin) { facebookID = pletformID; } } tipMessageText.text = "로그인 정보를 내려받는 중.."; form.AddField("google", googleID, System.Text.Encoding.UTF8); form.AddField("facebook", facebookID, System.Text.Encoding.UTF8); form.AddField("deviceModel", SystemInfo.deviceModel); form.AddField("deviceID", SystemInfo.deviceUniqueIdentifier); form.AddField("type", (int)loginType); string result = ""; string php = "Login.php"; yield return(StartCoroutine(WebServerConnectManager.Instance.WWWCoroutine(php, form, x => result = x))); JsonData jsonData = ParseCheckDodge(result); PlayerPrefs.SetString("userID", JsonParser.ToString(jsonData["id"].ToString())); if (loginType == LoginType.GoogleLogin) { PlayerPrefs.SetString("google", JsonParser.ToString(jsonData["google"].ToString())); } if (loginType == LoginType.FacebookLogin) { PlayerPrefs.SetString("facebook", JsonParser.ToString(jsonData["facebook"].ToString())); } // 아틀라스 캐싱 string atlasName = "Atlas_Product"; AssetBundleLoadAssetOperation r = AssetBundleManager.LoadAssetAsync("sprite/product", atlasName, typeof(UnityEngine.U2D.SpriteAtlas)); yield return(StartCoroutine(r)); UnityEngine.U2D.SpriteAtlas atlas = r.GetAsset <UnityEngine.U2D.SpriteAtlas>(); if (atlas != null) { if (!AssetLoader.cachedAtlasDic.ContainsKey(atlasName)) { AssetLoader.cachedAtlasDic.Add(atlasName, atlas); } } string atlasName2 = "Atlas_Material"; AssetBundleLoadAssetOperation r2 = AssetBundleManager.LoadAssetAsync("sprite/material", atlasName2, typeof(UnityEngine.U2D.SpriteAtlas)); yield return(StartCoroutine(r2)); UnityEngine.U2D.SpriteAtlas atlas2 = r2.GetAsset <UnityEngine.U2D.SpriteAtlas>(); if (atlas2 != null) { if (!AssetLoader.cachedAtlasDic.ContainsKey(atlasName2)) { AssetLoader.cachedAtlasDic.Add(atlasName2, atlas2); } } //// 게임 데이타 초기화 끝날 때 까지 대기 //while (!GameDataManager.isInitialized) // yield return null; if (User.Instance) { User.Instance.InitUserData(jsonData); } Debug.Log("유저 데이터 초기화"); while (!User.isInitialized) { yield return(null); } Debug.Log("완료"); // 유저 데이터 초기화 시작 StartCoroutine(UserDataManager.Instance.Init()); // 유저 데이터 초기화 완료 했는가 체크 while (!UserDataManager.isInitialized) { yield return(null); } tipMessageText.text = "왕국으로 진입중.."; Debug.Log("Login UserID : " + JsonParser.ToString(jsonData["id"])); //enterButton.SetActive(true); //if (onFadeOutStart != null) // onFadeOutStart(); ////페이드아웃 기다리는 시간 //yield return new WaitForSeconds(1.5f); yield return(StartCoroutine(LoadingManager.FadeOutScreen())); string nextSceneBundleName = "scene/lobby"; string nextSceneName = "Lobby"; AssetBundleLoadOperation operation = AssetBundleManager.LoadLevelAsync(nextSceneBundleName, nextSceneName, true); //// 몬스터 풀 초기화 끝났는가 체크 //while (!MonsterPool.Instance) // yield return null; //while (!MonsterPool.Instance.isInitialization) // yield return null; //while (!Battle.Instance || !Battle.Instance.isInitialized) // yield return null; while (!operation.IsDone()) { yield return(null); } versionText.gameObject.SetActive(false); messagePanel.SetActive(false); StopCoroutine(messageCoroutine()); //while (!UILoginManager.isFinished) // yield return null; Scene lobby = SceneManager.GetSceneByName("Lobby"); Scene login = SceneManager.GetSceneByName("Login"); Scene preLogin = SceneManager.GetSceneByName("PreLogin"); SceneManager.SetActiveScene(lobby); SceneManager.UnloadSceneAsync(login); SceneManager.UnloadSceneAsync(preLogin); }
protected void DrawEntries() { _entriesHelpRect = EditorHelper.ShowHideableHelpBox("GameFramework.LocalisationEditorWindow.Entries", "Entries contain a set of unique tags that identify the text that you want to localise. You can further associate different translations with these tags for the different languages that you have setup.", _entriesHelpRect); // filter EditorGUILayout.BeginHorizontal(); GUI.changed = false; EditorGUI.BeginChangeCheck(); _filter = EditorGUILayout.TextField(_filter, GuiStyles.ToolbarSearchField, GUILayout.ExpandWidth(true)); if (EditorGUI.EndChangeCheck()) { foreach (var entryReference in _entryReferenceList) { entryReference.MatchesFilter = entryReference.Key.IndexOf(_filter, StringComparison.OrdinalIgnoreCase) >= 0; } } if (GUILayout.Button("", string.IsNullOrEmpty(_filter) ? GuiStyles.ToolbarSearchFieldCancelEmpty : GuiStyles.ToolbarSearchFieldCancel, GUILayout.ExpandWidth(false))) { _filter = ""; GUIUtility.keyboardControl = 0; foreach (var entryReference in _entryReferenceList) { entryReference.MatchesFilter = true; } } EditorGUILayout.EndHorizontal(); if (_entryReferenceList.Count == 0) { GUILayout.Space(20); EditorGUILayout.LabelField("Create new localisation entries below.", GuiStyles.CenteredLabelStyle, GUILayout.ExpandWidth(true)); GUILayout.Space(20); } else { _entriesScrollPosition = EditorGUILayout.BeginScrollView(_entriesScrollPosition, false, false, GUILayout.ExpandHeight(false)); //Debug.Log(Event.current.type + ": " +_entriesScrollHeight + ", " + _entriesScrollPosition); // here we avoid using properties due to them being very slow! var indexForDeleting = -1; //var accumulativeHeightDrawn = 0; //var accumulativeSpace = 0; for (var i = 0; i < _entryReferenceList.Count; i++) { var entryReference = _entryReferenceList[i]; if (entryReference.MatchesFilter) { //// if top is below viewport or bottom is above then this item is not visible. For repaint events we need to use the //// previously recorded display state to avoid changing the number of controls drawn. ////if ((Event.current.type == EventType.Repaint && entryData.IsShown == false) || //// (Event.current.type != EventType.Repaint && //if (((Event.current.type != EventType.Layout && entryReference.IsShown == false) || // (Event.current.type == EventType.Layout && // (accumulativeHeightDrawn > _entriesScrollPosition.y + _entriesScrollHeight || // accumulativeHeightDrawn + entryReference.Height < _entriesScrollPosition.y))) && !entryReference.IsExpanded) //{ // accumulativeHeightDrawn += entryReference.Height; // accumulativeSpace += entryReference.Height; // entryReference.IsShown = false; //} //else //{ // // fill space from skipped. // if (accumulativeSpace > 0) GUILayout.Space(accumulativeSpace); // accumulativeSpace = 0; // draw the displayed item entryReference.IsShown = true; var localisationEntry = _targetLocalisationData.GetEntry(_entryReferenceList[i].Key); EditorGUILayout.BeginHorizontal(); EditorGUI.indentLevel++; //var oldExpanded = entryReference.IsExpanded; entryReference.IsExpanded = EditorGUILayout.Foldout(entryReference.IsExpanded, localisationEntry.Key); // if we are not using a static default height (see below) then we need to flag changes to the expanded state, and in OnInspectorGUI // call repaint within a 'if (Event.current.type == EventType.Repaint && _updatePostRepaint)' check. This so that if an entry // decreases in size we correctly draw items that might previously have been hidden. //if (entryReference.IsExpanded != oldExpanded) // force repaint on changes incase new items become visable due to collapsing // _updatePostRepaint = true; EditorGUI.indentLevel--; if (GUILayout.Button("-", EditorStyles.miniButton, GUILayout.Width(GuiStyles.RemoveButtonWidth))) { indexForDeleting = i; break; } EditorGUILayout.EndHorizontal(); //if (Event.current.type == EventType.Repaint) //entryData.Height = (int)GUILayoutUtility.GetLastRect().height; // only works on repaint. entryReference.Height = _entriesDefaultRowHeight; // handle expended status if (entryReference.IsExpanded) { EditorGUILayout.BeginVertical(); EditorGUI.indentLevel++; for (var li = 0; li < localisationEntry.Languages.Length; li++) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(_targetLocalisationData.Languages[li].Name, GUILayout.Width(100)); EditorGUI.BeginChangeCheck(); var lang = EditorGUILayout.TextArea(localisationEntry.Languages[li], GuiStyles.WordWrapStyle, GUILayout.Width(Screen.width - 100 - 60 - 50)); if (EditorGUI.EndChangeCheck()) { Undo.RecordObject(_targetLocalisationData, "Edit Localisation Entry"); localisationEntry.Languages[li] = lang; _targetChanged = true; } // TODO: Move to a callback so we don't block the UI if (li > 0 && GUILayout.Button("Translate", EditorStyles.miniButton, GUILayout.Width(60))) { var sourceCode = _targetLocalisationData.Languages[0].Code; if (!string.IsNullOrEmpty(sourceCode)) { var targetCode = _targetLocalisationData.Languages[li].Code; if (!string.IsNullOrEmpty(targetCode)) { var sourceText = localisationEntry.Languages[0]; string url = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + sourceCode + "&tl=" + targetCode + "&dt=t&q=" + WWW.EscapeURL(sourceText); var wwwForm = new WWWForm(); wwwForm.AddField("username", ""); //var headers = new Dictionary<string, string>(); wwwForm.headers.Add("content-type", "application/json"); var www = new WWW(url, wwwForm); while (!www.isDone) { ; } if (www.error != null) { Debug.LogError(www.error); } else { Debug.Log("Google Translate Response:" + www.text); var json = ObjectModel.Internal.SimpleJSON.JSONNode.Parse(www.text); if (json != null) { var translation = ""; for (var lines = 0; lines < json[0].Count; lines++) { // Dig through and take apart the text to get to the good stuff. var translatedText = json[0][lines][0].ToString(); if (translatedText.Length > 2) { translatedText = translatedText.Substring(1, translatedText.Length - 2); } if (translation.Length > 0) { translation += "\n"; } translation += translatedText.Replace("\\n", "").Replace("\\\"", "\""); } Undo.RecordObject(_targetLocalisationData, "Edit Localisation Entry"); localisationEntry.Languages[li] = translation; _targetChanged = true; } else { Debug.LogError("Unable to parse json response"); } } } else { EditorUtility.DisplayDialog("Localisation Import", "There is no code specified for the language '" + _targetLocalisationData.Languages[li].Name + "'.\n\nPlease enter under the languages tab.", "Ok"); } } else { EditorUtility.DisplayDialog("Localisation Translate", "There is no code specified for the language '" + _targetLocalisationData.Languages[0].Name + "'.\n\nPlease enter under the languages tab.", "Ok"); } } EditorGUILayout.EndHorizontal(); } EditorGUI.indentLevel--; EditorGUILayout.EndVertical(); // repaint events will give a new correct size for the last drawn rect so record here. //if (Event.current.type == EventType.Repaint) // entryReference.Height += (int)GUILayoutUtility.GetLastRect().height; // only works on repaint. //} //accumulativeHeightDrawn += entryReference.Height; // Debug.Log(entryData.LocalisationEntry.Key + ", " + accumulativeHeightDrawn); } } } //if (accumulativeSpace > 0) GUILayout.Space(accumulativeSpace); //Debug.Log(accumulativeHeightDrawn); EditorGUILayout.EndScrollView(); //if (Event.current.type == EventType.Repaint) // _entriesScrollHeight = GUILayoutUtility.GetLastRect().height; // only works on repaint. // delay deleting to avoid editor issues. if (indexForDeleting != -1) { var keyToDelete = _entryReferenceList[indexForDeleting].Key; if (EditorUtility.DisplayDialog("Delete Entry?", String.Format("Are you sure you want to delete the entry '{0}?'", keyToDelete), "Yes", "No")) { Undo.RecordObject(_targetLocalisationData, "Delete Localisation Entry"); _targetLocalisationData.RemoveEntry(keyToDelete); _entryReferenceList.RemoveAt(indexForDeleting); _targetChanged = true; } } } // add functionality EditorGUILayout.BeginHorizontal(); bool entryAddPressed = false; if (GUI.GetNameOfFocusedControl() == "EntryAdd" && Event.current.type == EventType.KeyDown && (Event.current.keyCode == KeyCode.KeypadEnter || Event.current.keyCode == KeyCode.Return)) { entryAddPressed = true; Event.current.Use(); } GUI.SetNextControlName("EntryAdd"); _newKey = EditorGUILayout.TextField("", _newKey, GUILayout.ExpandWidth(true)); var isValidEntry = !string.IsNullOrEmpty(_newKey) && !_targetLocalisationData.ContainsEntry(_newKey); GUI.enabled = isValidEntry; if (entryAddPressed || GUILayout.Button(new GUIContent("Add", "Add the specified entry to the list"), EditorStyles.miniButton, GUILayout.Width(100))) { if (isValidEntry) { Undo.RecordObject(_targetLocalisationData, "Add Localisation Entry"); _targetLocalisationData.AddEntry(_newKey); _targetChanged = true; _languagesCount = _targetLocalisationData.Languages.Count; // set incase a first language was autocreated. var insertIndex = 0; var scrollOffset = 0; for (; insertIndex < _entryReferenceList.Count; insertIndex++) { if (_newKey.CompareTo(_entryReferenceList[insertIndex].Key) < 0) { break; } else { scrollOffset += _entryReferenceList[insertIndex].Height; } } _entryReferenceList.Insert(insertIndex, new EntryReference() { Key = _newKey, MatchesFilter = _newKey.IndexOf(_filter + "", StringComparison.OrdinalIgnoreCase) >= 0, IsExpanded = true }); _entriesScrollPosition.y = scrollOffset; var lastDot = _newKey.LastIndexOf(".", StringComparison.Ordinal); if (lastDot == -1) { _newKey = ""; } else { _newKey = _newKey.Substring(0, lastDot + 1); } } GUI.FocusControl("EntryAdd"); } GUI.enabled = true; EditorGUILayout.EndHorizontal(); GUILayout.Space(5); GUI.enabled = _entryReferenceList.Count > 0; if (GUILayout.Button(new GUIContent("Delete All", "Delete All entries"), EditorStyles.miniButton, GUILayout.Width(100))) { Undo.RecordObject(_targetLocalisationData, "Delete Localisation Entry"); _targetLocalisationData.ClearEntries(); _entryReferenceList.Clear(); _targetChanged = true; } GUI.enabled = true; }
private void CheckUpdate() { //检查是否有patchIndex文件,并读取内容 var indexFile = UResources.ReqFile(INDEX_FILE_NAME); if (indexFile != null) { string fileJson = DESFileUtil.ReadAllText(indexFile.FullName, DESKey.DefaultKey, DESKey.DefaultIV); _patchIndexLocal = new PatchIndex(this.VersionCode, JObject.Parse(fileJson)); if (_patchIndexLocal.Version != this.VersionCode) { UpdaterLog.Log("发现patchIndex中的主版本不等于目前的主版本,说明刚经历过主包更新,清空补丁"); foreach (var file in ResManager.Ins.DownloadedFiles.Values) { File.Delete(file.FullName); } ResManager.Ins.ReadDownloadDir(); _patchIndexLocal = new PatchIndex(); } } else { _patchIndexLocal = new PatchIndex(); } //构建检查更新需要的表单 JObject json = new JObject(); json["Version"] = this.VersionCode; json["PatchVersion"] = _patchIndexLocal.PatchVersion; if (CustomData != null) { foreach (var kv in CustomData) { json[kv.Key.ToString()] = kv.Value.ToString(); } } WWWForm form = new WWWForm(); form.AddField("Data", json.ToString()); HttpManager.Post(CheckUpdateUrl, form, (error, www) => { if (!string.IsNullOrEmpty(error)) { Listener.OnError(error); return; } UpdaterLog.Log(www.text); JObject responseJObj = JObject.Parse(www.text); _updateType = (UpdateType)(responseJObj["Type"].OptInt(0)); switch (_updateType) { case UpdateType.NoUpdate: _patchIndexNew = new PatchIndex(this.VersionCode, responseJObj); //没有找到更新,验证文件 Listener.OnVerifyStart(); if (VerifyPatches()) { Listener.OnVerifySuccess(); Listener.OnPassUpdate(); } else { Listener.OnVerifyFail(); } break; case UpdateType.MainPak: _mainPakIndexFromServer = new MainPakIndex(this.VersionCode, responseJObj); Listener.OnFindMainUpdate(_mainPakIndexFromServer.Info); break; case UpdateType.Patch: _patchIndexNew = new PatchIndex(this.VersionCode, responseJObj); if (Listener != null) { Listener.OnFindPatchUpdate(_patchIndexNew.PatchInfo, _patchIndexNew.TotalPatchSize); } break; } }); }
public void AddData(string key, string value) { _wwwForm.AddField(key, value); }
public IEnumerator UploadPNG() { // We should only read the screen buffer after rendering is complete yield return(new WaitForEndOfFrame()); // Create a texture the size of the screen, RGB24 format int width = Screen.width; int height = Screen.height; Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false); // Read screen contents into the texture tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); //iterate through the pixels and see if the pixel coordinates are within the shape that we are carving out, //make them transparent if they meet the condition for (int x = 0; x < tex.width; x++) { for (int y = 0; y < tex.height; y++) { //get the color of the pixel at the current coordinates Color colorOfPixel = tex.GetPixel(x, y); //if the pixel is already transparent, go to the next iteration if (colorOfPixel.a == 0) { continue; } if (colorOfPixel != color) { colorOfPixel.a = 0; tex.SetPixel(x, y, colorOfPixel); } } } tex.Apply(); // Encode texture into PNG byte[] bytes = tex.EncodeToPNG(); Object.Destroy(tex); // For testing purposes, also write to a file in the project folder File.WriteAllBytes(Application.dataPath + "/b.png", bytes); // Create a Web Form WWWForm form = new WWWForm(); form.AddField("frameCount", Time.frameCount.ToString()); form.AddBinaryData("fileUpload", bytes); // Upload to a cgi script WWW w = new WWW("http://localhost/cgi-bin/env.cgi?post", form); yield return(w); if (w.error != null) { Debug.Log(w.error); } else { Debug.Log("Finished Uploading Screenshot"); } }
public IEnumerator expStart(string key) { bool VRenable = VR.isOn; // string json = JsonUtility.ToJson(user); // Debug.Log("hjfbsf"); var token = PlayerPrefs.GetString("token"); var url = "https://vrlabserver.herokuapp.com/api/result/start/" + token; Debug.Log(url); // var req = new UnityWebRequest(url, "POST"); // byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(key); // req.uploadHandler = (UploadHandler)new UploadHandlerRaw(key); // req.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); // req.SetRequestHeader("Content-Type", "application/json"); //Send the request then wait here until it returns WWWForm form = new WWWForm(); form.AddField("key", key); using (UnityWebRequest www = UnityWebRequest.Post(url, form)) { yield return(www.SendWebRequest()); if (www.isNetworkError || www.isHttpError) { Debug.Log(www.error); } else { // Debug.Log("Form upload complete!"); PlayerPrefs.SetString("key", key); Debug.Log(www.downloadHandler.text); var res = new Response(); JsonUtility.FromJsonOverwrite(www.downloadHandler.text, res); Debug.Log(res.type); if (res.type == "simple-pendulum") { if (VRenable == false) { SceneManager.LoadScene("Simple Pendulum"); } else { SceneManager.LoadScene("Simple Pendulum VR"); } } else if (res.type == "hookes-law") { if (VRenable == false) { SceneManager.LoadScene("Hookes Law"); } else { SceneManager.LoadScene("Hookes Law VR"); } } else { KeyError.text = "Invalid Key"; } } } // yield return req.SendWebRequest(); // if (req.isNetworkError){ // Debug.Log("Error While Sending: " + req.error); // LoginError.text = "Network issues"; // } // else if(req.isHttpError){ // Debug.Log("Error While Sending: " + req.error); // var res=new Response(); // JsonUtility.FromJsonOverwrite(req.downloadHandler.text, res); // Debug.Log("Error: " + res.message); // LoginError.text = res.message; // } // else{ // var res=new Response(); // Debug.Log(res); // if (res.type == "simple-pendulum") // { // if (VRenable == false) // SceneManager.LoadScene("Simple Pendulum"); // else // SceneManager.LoadScene("Simple Pendulum VR"); // } // else if (res.type == "hookes-law") // { // if (VRenable == false) // SceneManager.LoadScene("Hookes Law"); // else // SceneManager.LoadScene("Hookes Law VR"); // } // else // KeyError.text = "Invalid Key"; // JsonUtility.FromJsonOverwrite(req.downloadHandler.text, res); // Inputs.SetActive(false); // KeyInput.SetActive(true); }
private IEnumerator DQItemList() { string url = Link.url + "DQuest"; WWWForm form = new WWWForm(); form.AddField("MY_ID", PlayerPrefs.GetString(Link.ID)); //form.AddField ("SHOP_JENIS", "SPECIAL"); WWW www = new WWW(url, form); yield return(www); if (www.error == null) { Debug.Log(www.text); var jsonString = JSON.Parse(www.text); //PlayerPrefs.SetString (Link.FOR_CONVERTING, jsonString["ID_SHOP_SPECIAL"]); if (int.Parse(jsonString["code"]) == 1) { for (int x = 0; x < int.Parse(jsonString["count"]); x++) { int lol = 0; var number = int.TryParse(jsonString["data"][x]["Quest_Done"], out lol); if (number) { if (lol == 1) { string String = jsonString["data"][x]["Type"]; if (String == "Summon") { PlayerPrefs.SetString("SummonMissionStats", "FALSE"); } if (String == "SingleMode") { PlayerPrefs.SetString("SoloMissionStats", "FALSE"); } if (String == "Catch") { PlayerPrefs.SetString("CatchMissionStats", "FALSE"); } } else { string String = jsonString["data"][x]["Type"]; if (String == "Summon") { PlayerPrefs.SetString("SummonMissionStats", "TRUE"); PlayerPrefs.SetString("SummonMissionQD", jsonString["data"][x]["ID"]); } if (String == "SingleMode") { PlayerPrefs.SetString("SoloMissionStats", "TRUE"); PlayerPrefs.SetString("SoloMissionQD", jsonString["data"][x]["ID"]); } if (String == "Catch") { PlayerPrefs.SetString("CatchMissionStats", "TRUE"); PlayerPrefs.SetString("CatchMissionQD", jsonString["data"][x]["ID"]); } } // Debug.Log(PlayerPrefs.GetString("SoloMissionQD")); } else { } } } else { Debug.Log("NoMission"); } yield return(new WaitForSeconds(1)); SceneManagerHelper.LoadScene(Link.Home); } else { Debug.Log(www.text); Debug.Log("NoMission"); } }
public override System.Collections.IEnumerator Execute(UTContext context) { if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebPlayer || EditorUserBuildSettings.activeBuildTarget == BuildTarget.WebPlayerStreamed) { Debug.LogWarning("You have currently set the build target to 'Web Player'. This may cause interference with actions that access the internet. If you get an error message about cross domain policy from this action, switch the target to 'PC and Mac Standalone' and try again."); } var theNexusUrl = nexusUrl.EvaluateIn(context); if (string.IsNullOrEmpty(theNexusUrl)) { throw new UTFailBuildException("You need to specify the nexus URL", this); } var theRepoId = repositoryId.EvaluateIn(context); if (string.IsNullOrEmpty(theRepoId)) { throw new UTFailBuildException("You need to specify the repository id.", this); } var theUserName = userName.EvaluateIn(context); var thePassword = password.EvaluateIn(context); var theGroupId = groupId.EvaluateIn(context); if (string.IsNullOrEmpty(theGroupId)) { throw new UTFailBuildException("You need to specify the group id.", this); } var theArtifactId = artifactId.EvaluateIn(context); if (string.IsNullOrEmpty(theArtifactId)) { throw new UTFailBuildException("You need to specify the artifact id.", this); } var theVersion = version.EvaluateIn(context); if (string.IsNullOrEmpty(theVersion)) { throw new UTFailBuildException("You need to specify the version.", this); } var thePackaging = packaging.EvaluateIn(context); if (string.IsNullOrEmpty(thePackaging)) { throw new UTFailBuildException("You need to specify the packaging.", this); } var theExtension = extension.EvaluateIn(context); var theClassifier = classifier.EvaluateIn(context); var theInputFileName = inputFileName.EvaluateIn(context); if (string.IsNullOrEmpty(theInputFileName)) { throw new UTFailBuildException("You need to specify the input file name.", this); } if (Directory.Exists(theInputFileName)) { throw new UTFailBuildException("The specified input file " + theInputFileName + " is a directory.", this); } if (!File.Exists(theInputFileName)) { throw new UTFailBuildException("The specified input file " + theInputFileName + " does not exist.", this); } WWWForm form = new WWWForm(); form.AddField("r", theRepoId); form.AddField("g", theGroupId); form.AddField("a", theArtifactId); form.AddField("v", theVersion); if (!string.IsNullOrEmpty(thePackaging)) { form.AddField("p", thePackaging); } if (!string.IsNullOrEmpty(theClassifier)) { form.AddField("c", theClassifier); } if (!string.IsNullOrEmpty(theExtension)) { form.AddField("e", theExtension); } var bytes = File.ReadAllBytes(theInputFileName); form.AddBinaryData("file", bytes, new FileInfo(theInputFileName).Name); var hash = UTils.ComputeHash(bytes); if (UTPreferences.DebugMode) { Debug.Log("SHA1-Hash of file to upload: " + hash); } string authString = theUserName + ":" + thePassword; var authBytes = System.Text.UTF8Encoding.UTF8.GetBytes(authString); var headers = new Hashtable(); foreach (var key in form.headers.Keys) { headers.Add(key, form.headers [key]); } headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(authBytes)); var url = UTils.BuildUrl(theNexusUrl, "/service/local/artifact/maven/content"); // using (var www = new WWW (url, form.data, //#if UNITY_WP8 // PortUtil.HashtableToDictionary<string, string>(headers) //#else // headers //#endif // )) // { // do { // yield return ""; // } while(!www.isDone && !context.CancelRequested); // if (UTPreferences.DebugMode) { // Debug.Log ("Server Response: " + www.text); // } // } if (!context.CancelRequested) { using (var wc = new WebClient()) { if (!string.IsNullOrEmpty(theUserName)) { Debug.Log("Setting credentials"); wc.Credentials = new NetworkCredential(theUserName, thePassword); } Uri uri = new Uri(UTils.BuildUrl(theNexusUrl, "/service/local/artifact/maven/resolve?") + "g=" + Uri.EscapeUriString(theGroupId) + "&a=" + Uri.EscapeUriString(theArtifactId) + "&v=" + Uri.EscapeUriString(theVersion) + "&r=" + Uri.EscapeUriString(theRepoId) + "&p=" + Uri.EscapeUriString(thePackaging) + (!string.IsNullOrEmpty(theClassifier) ? "&c=" + Uri.EscapeUriString(theClassifier) : "") + (!string.IsNullOrEmpty(theExtension) ? "&e=" + Uri.EscapeUriString(theExtension) : "")); var downloadFinished = false; var error = false; string result = null; wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) { downloadFinished = true; error = e.Error != null; if (error) { Debug.LogError("An error occured while downloading artifact information. " + e.Error.Message, this); } else { result = (string)e.Result; } }; wc.DownloadStringAsync(uri); do { yield return(""); if (context.CancelRequested) { wc.CancelAsync(); } } while(!downloadFinished); if (!context.CancelRequested) { if (!error) { if (UTPreferences.DebugMode) { Debug.Log("Server Response: " + result); } if (result.Contains("<sha1>" + hash + "</sha1>")) { Debug.Log("Successfully uploaded artifact " + theInputFileName + ".", this); } else { throw new UTFailBuildException("Upload failed. Checksums do not match.", this); } } else { throw new UTFailBuildException("Artifact verification failed", this); } } } } }
private IEnumerator registerIEnumerator() { string url = Link.url + "register"; WWWForm form = new WWWForm(); form.AddField(Link.DEVICE_ID, device_id); form.AddField(Link.USER_NAME, userName.text); form.AddField(Link.FULL_NAME, fullName.text); form.AddField(Link.EMAIL, email.text); form.AddField(Link.PASSWORD, password.text); form.AddField("fbstats", 1); WWW www = new WWW(url, form); yield return(www); if (www.error == null) { var jsonString = JSON.Parse(www.text); PlayerPrefs.SetInt("informasiServer", int.Parse(jsonString ["code"])); switch (PlayerPrefs.GetInt("informasiServer")) { case 1: // StartCoroutine (loginIEnumerator(email.text,password.text,"EMAIL", "TRUE")); if (PlayerPrefs.GetString(Link.LOGIN_BY) == "FB") { //PlayerPrefs.SetString ("Tutorialman", "TRUE"); // yield return new WaitForSeconds(5); StartCoroutine(cekLoginByFB()); print("Login After Register"); } else if (PlayerPrefs.GetString(Link.LOGIN_BY) == "Google") { //PlayerPrefs.SetString ("Tutorialman", "TRUE"); // yield return new WaitForSeconds(5); StartCoroutine(cekLoginByGoogle()); print("Login After Register"); } else { StartCoroutine(AnimasiInformasiServer("Check Your Email for Verification")); this.GetComponent <Animator>().Play("login"); } // PlayerPrefs.SetString ("Tutorialman", "TRUE"); break; case 2: StartCoroutine(AnimasiInformasiServer("This Email Already Registered")); break; case 3: StartCoroutine(AnimasiInformasiServer("This User Name Already Taken")); break; case 5: StartCoroutine(AnimasiInformasiServer("Invalid Email Format")); break; case 6: StartCoroutine(AnimasiInformasiServer("Invalid Password Format")); break; case 7: StartCoroutine(AnimasiInformasiServer("Check Your Email for Verification")); break; default: StartCoroutine(AnimasiInformasiServer("Something Wrong. Try Again Later")); break; } } else { StartCoroutine(AnimasiInformasiServer("Something Wrong. Try Again Later")); } }
public IEnumerator save(string Datenbank_URL, int player_id) { //Debug.Log ("Versuche zu speichern " + Datenbank_URL + "save_player.php"); WWWForm LoginForm = new WWWForm(); LoginForm.AddField("player_id", player_id); LoginForm.AddField("hp", hp); LoginForm.AddField("maxhp", maxhp); LoginForm.AddField("mana", mana); LoginForm.AddField("maxmana", maxmana); LoginForm.AddField("xp", xp); LoginForm.AddField("lvl", lvl); LoginForm.AddField("gold", gold); LoginForm.AddField("pwr", pwr); LoginForm.AddField("armor", armor); LoginForm.AddField("agility", agility); LoginForm.AddField("posx", "" + pos.x); LoginForm.AddField("posy", "" + pos.y); LoginForm.AddField("lastposx", "" + lastpos.x); LoginForm.AddField("lastposy", "" + lastpos.y); //public inventory inv; //public List<items> Equip = new List<items> (); WWW web = new WWW(Datenbank_URL + "save_player.php", LoginForm); yield return(web); //Debug.Log ("Hab gespeichert" + web.text); StartCoroutine(save_inv(Datenbank_URL, Player_ID)); }
public static void AddFieldEx(this WWWForm form, string fieldName, int value) { form.AddField(fieldName, value); }
private IEnumerator loginIEnumerator(string email, string pass, string login_by) { string url = Link.url + "login"; WWWForm form = new WWWForm(); form.AddField(Link.DEVICE_ID, device_id); form.AddField(Link.EMAIL, email); form.AddField(Link.PASSWORD, pass); form.AddField("Version", version); WWW www = new WWW(url, form); yield return(www); Debug.Log(www.text); if (www.error == null) { var jsonString = JSON.Parse(www.text); PlayerPrefs.SetInt("informasiServer", int.Parse(jsonString ["code"])); switch (PlayerPrefs.GetInt("informasiServer")) { case 1: if (int.Parse(jsonString["data"]["tfinish"]) == 0) { PlayerPrefs.SetString("PLAY_TUTORIAL", "TRUE"); } else { //PlayerPrefs.DeleteKey ("Tutorialman"); PlayerPrefs.SetString("PLAY_TUTORIAL", "FALSE"); } PlayerPrefs.SetString(Link.ID, jsonString ["data"] ["id"]); PlayerPrefs.SetString(Link.LOGIN_BY, login_by); PlayerPrefs.SetString(Link.STATUS_LOGIN, "true"); PlayerPrefs.SetString(Link.EMAIL, jsonString ["data"] ["email"]); PlayerPrefs.SetString(Link.USER_NAME, jsonString ["data"] ["user_name"]); PlayerPrefs.SetString(Link.FULL_NAME, jsonString ["data"] ["full_name"]); PlayerPrefs.SetString(Link.AP, jsonString ["data"] ["ap"]); PlayerPrefs.SetString(Link.AR, jsonString ["data"] ["ar"]); PlayerPrefs.SetString(Link.PASSWORD, pass); PlayerPrefs.SetString(Link.DEVICE_ID, device_id); PlayerPrefs.SetString(Link.Stage, jsonString["data"]["Stage"]); PlayerPrefs.SetString(Link.IBURU, jsonString["data"]["iklan_buru"]); PlayerPrefs.SetString(Link.IGOLD, jsonString["data"]["iklan_gold"]); PlayerPrefs.SetString(Link.IENERGY, jsonString["data"]["iklan_energy"]); // PlayerPrefs.SetString("BonusEnergy", jsonString ["data"] ["BonusEnergy"]); // var energy = int.Parse(jsonString ["data"] ["energy"]) + int.Parse(jsonString ["data"] ["BonusEnergy"]); PlayerPrefs.SetString("EnergyCombo", energy.ToString()); PlayerPrefs.SetString("curexp", jsonString["data"]["xpp"]); PlayerPrefs.SetString("tarexp", jsonString["data"]["targetexplevel"]); PlayerPrefs.SetString(Link.ENERGY, jsonString["data"]["energy"]); PlayerPrefs.SetString("MaxE", jsonString["data"]["MaxEnergy"]); PlayerPrefs.SetString("PlayerLevel", jsonString["data"]["PlayerLevel"]); PlayerPrefs.SetString(Link.GOLD, jsonString["data"]["coin"]); PlayerPrefs.SetString(Link.SOUL_STONE, jsonString["data"]["soulstone"]); PlayerPrefs.SetString(Link.COMMON, jsonString["data"]["common"]); PlayerPrefs.SetString(Link.RARE, jsonString["data"]["rare"]); PlayerPrefs.SetString(Link.LEGENDARY, jsonString["data"]["legendary"]); if (login_by != "FB") { int hasil; var hasilnya = int.TryParse(jsonString["data"]["image"], out hasil); if (hasilnya) { PlayerPrefs.DeleteKey("Base64PictureProfile"); } else { StartCoroutine(showAvatar()); } } StartCoroutine(AchievementList()); // yield return new WaitForSeconds(.5f); break; case 2: StartCoroutine(AnimasiInformasiServer("Wrong Password")); PlayerPrefs.DeleteKey(Link.LOGIN_BY); PlayerPrefs.DeleteKey(Link.STATUS_LOGIN); break; case 3: StartCoroutine(AnimasiInformasiServer("Email Not Registered Yet. Please Register")); PlayerPrefs.DeleteKey(Link.LOGIN_BY); PlayerPrefs.DeleteKey(Link.STATUS_LOGIN); break; case 4: StartCoroutine(AnimasiInformasiServer("This User Already Login On Another Device")); PlayerPrefs.DeleteKey(Link.LOGIN_BY); PlayerPrefs.DeleteKey(Link.STATUS_LOGIN); break; case 5: StartCoroutine(AnimasiInformasiServer("Invalid Email Format")); PlayerPrefs.DeleteKey(Link.LOGIN_BY); PlayerPrefs.DeleteKey(Link.STATUS_LOGIN); break; case 6: StartCoroutine(AnimasiInformasiServer("Check Your Email for Verification")); PlayerPrefs.DeleteKey(Link.LOGIN_BY); PlayerPrefs.DeleteKey(Link.STATUS_LOGIN); break; case 71: StartCoroutine(AnimasiInformasiServer("Please Update to the newest version")); // PlayerPrefs.DeleteKey(Link.LOGIN_BY); // PlayerPrefs.DeleteKey(Link.STATUS_LOGIN); Application.OpenURL(jsonString ["Url"]); break; default: StartCoroutine(AnimasiInformasiServer("Something Wrong. Try Again Later")); PlayerPrefs.DeleteKey(Link.LOGIN_BY); PlayerPrefs.DeleteKey(Link.STATUS_LOGIN); break; } } else { StartCoroutine(AnimasiInformasiServer("Something Wrong. Try Again Later")); } }
IEnumerator upload_data_to_php_file_ienumerator() { WWWForm form = new WWWForm(); form.AddField("image", "image" + screenshot_taker.image_index + "added"); form.AddField("image_url", Application.dataPath + "/captured_images/per_session_images/CameraScreenshot" + screenshot_taker.image_index + ".png"); if (port_forwarding_ip_address.text == "") { //ipaddress = "http://localhost/object_detection_connection.php"; Debug.Log(" using firebase database now"); } else if (port_forwarding_ip_address.text == "localhost") { ipaddress = "http://localhost/object_detection_connection.php"; } else { ipaddress = "http://" + port_forwarding_ip_address.text + "/object_detection_connection.php"; } WWW www = new WWW(ipaddress, form); yield return(www); if (www.text == "") { Debug.Log(" image not uploaded to php file"); } else { Debug.Log(" image successfully sent to php file"); } //using (UnityWebRequest www2 = UnityWebRequest.Post(ipaddress,form)) //{ // yield return www2.SendWebRequest(); // if (www2.isNetworkError || www2.isHttpError) // { // Debug.Log(www2.error); // } // else // { // Debug.Log(www2.downloadHandler.text); // } //} // Encode texture into PNG //byte[] bytes = screenshot_taker.renderResult.EncodeToJPG(); // Create a Web Form //WWWForm form = new WWWForm(); //form.AddField("frameCount", Time.frameCount.ToString()); //form.AddBinaryData("image_blob_data", bytes, "captured_image.jpg", "image/jpg"); // Upload to a cgi script //using (var w = UnityWebRequest.Post("/opt/lampp/cgi-bin/test-cgi", form)) //{ // w.chunkedTransfer = false; // yield return w.SendWebRequest(); // if (w.error != null) // { // print("error" + w.error); // } // else // { // print("Finished Uploading Captured Image: " + w.responseCode); // } //} // data="hi"; //JsonUtility.ToJson(data); //Debug.Log(data); //using (UnityWebRequest www_json = UnityWebRequest.Put("0.0.0.0:5000/predict", data)) //{ // www_json.SetRequestHeader("Content-Type", "application/json"); // //Debug.Log(""); //} //######################################trying this out still for json direct send to flask_app.py string json = "hi"; var jsonBinary = System.Text.Encoding.UTF8.GetBytes(json); DownloadHandlerBuffer downloadHandlerBuffer = new DownloadHandlerBuffer(); UploadHandlerRaw uploadHandlerRaw = new UploadHandlerRaw(jsonBinary); uploadHandlerRaw.contentType = "application/json"; UnityWebRequest www_json = new UnityWebRequest("0.0.0.0:5000/predict", "POST", downloadHandlerBuffer, uploadHandlerRaw); yield return(www_json.SendWebRequest()); if (www_json.isNetworkError) { Debug.LogError(string.Format("{0}: {1}", www_json.url, www_json.error)); } else { Debug.Log(string.Format("Response: {0}", www_json.downloadHandler.text)); } }
private IEnumerator OnGM() { string url = Link.url + "registerGM"; WWWForm form = new WWWForm(); form.AddField(Link.DEVICE_ID, device_id); form.AddField("fbstats", holder.stats); WWW www = new WWW(url, form); yield return(www); Debug.Log(www.text); if (www.error == null) { var jsonString = JSON.Parse(www.text); Debug.Log(www.text); PlayerPrefs.SetInt("informasiServer", int.Parse(jsonString["code"])); PlayerPrefs.SetString(Link.EMAIL, jsonString["email"]); PlayerPrefs.SetString(Link.PASSWORD, jsonString["pass"]); PlayerPrefs.SetString("GMode", jsonString["gm"]); switch (PlayerPrefs.GetInt("informasiServer")) { case 1: // StartCoroutine (loginIEnumerator(email.text,password.text,"EMAIL", "TRUE")); if (PlayerPrefs.GetString(Link.LOGIN_BY) == "FB") { //PlayerPrefs.SetString ("Tutorialman", "TRUE"); StartCoroutine(cekLoginByFB()); } else { StartCoroutine(loginIEnumerator(PlayerPrefs.GetString(Link.EMAIL), PlayerPrefs.GetString(Link.PASSWORD), "EMAIL")); PlayerPrefs.SetString("GMode", "1"); } // PlayerPrefs.SetString ("Tutorialman", "TRUE"); break; case 2: StartCoroutine(AnimasiInformasiServer("This Email Already Registered")); break; case 3: StartCoroutine(AnimasiInformasiServer("This User Name Already Taken")); break; case 5: StartCoroutine(AnimasiInformasiServer("Invalid Email Format")); break; case 6: StartCoroutine(AnimasiInformasiServer("Invalid Password Format")); break; case 7: StartCoroutine(AnimasiInformasiServer("Check Your Email for Verification")); break; default: StartCoroutine(AnimasiInformasiServer("Something Wrong. Try Again Later")); break; } } else { StartCoroutine(AnimasiInformasiServer("Something Wrong. Try Again Later")); } }
/// <summary> /// Connect with database /// </summary> /// <returns></returns> IEnumerator RegisterProcess(string user, string nick, string pass, string email) { isRequesting = true; SetLogText(""); //Used for security check for authorization to modify database string hash = Md5Sum(user + pass + bl_LoginProDataBase.Instance.SecretKey).ToLower(); LoadingUI.SetActive(true); //Assigns the data we want to save //Where -> Form.AddField("name" = matching name of value in SQL database WWWForm mForm = new WWWForm(); mForm.AddField("name", user); // adds the login name to the form mForm.AddField("nick", nick); // adds the nick name to the form mForm.AddField("password", pass); // adds the player password to the form mForm.AddField("kills", 0); // adds the kill total to the form mForm.AddField("deaths", 0); // adds the death Total to the form mForm.AddField("score", 0); // adds the score Total to the form mForm.AddField("coins", bl_GameData.Instance.VirtualCoins.InitialCoins); if (bl_LoginProDataBase.Instance.RequiredEmailVerification && !string.IsNullOrEmpty(email)) { mForm.AddField("email", email); } else { mForm.AddField("email", "none"); } mForm.AddField("multiemail", bl_LoginProDataBase.Instance.CanRegisterSameEmailInt()); mForm.AddField("emailVerification", bl_LoginProDataBase.Instance.RequiereVerification()); mForm.AddField("uIP", currentIP); mForm.AddField("hash", hash); // adds the security hash for Authorization //Creates instance of WWW to runs the PHP script to save data to mySQL database using (UnityWebRequest www = UnityWebRequest.Post(bl_LoginProDataBase.Instance.GetUrl(bl_LoginProDataBase.URLType.Register), mForm)) { yield return(www.SendWebRequest()); if (www.error == null) { string result = www.downloadHandler.text; if (result.Contains("success") == true) { //show success ChangePanel(4); SetLogText("Register success!"); } else { Debug.Log(www.downloadHandler.text); ErrorType(www.downloadHandler.text); } } else { Debug.Log("Error:" + www.error); } LoadingUI.SetActive(false); } isRequesting = false; }
// Update the view count as often as possible private IEnumerator UpdateViews() { while (Connected && IRC.ChannelName.Length > 0) { var form = new WWWForm(); form.AddField("name", "value"); var headers = form.headers; var url = "https://api.twitch.tv/kraken/streams/" + IRC.ChannelName; headers["Client-ID"] = "REMOVED FOR GITHUB"; //#TODO Replace with your Client-ID var www = new WWW(url, null, headers); yield return(www); if (string.IsNullOrEmpty(www.error)) { var obj = JsonUtility.FromJson <ChannelDataFull>(www.text); if (obj != null) { if (obj.stream != null) { if (obj.stream.channel != null) { if (ChannelNameTextMesh != null) { var text = ""; if (!string.IsNullOrEmpty(obj.stream.channel.display_name)) { text = string.Format("#{0}", obj.stream.channel.display_name); } else if (!string.IsNullOrEmpty(obj.stream.channel.name)) { text = string.Format("#{0}", obj.stream.channel.name); } else { text = "Not Streaming"; } ChannelNameTextMesh.text = text; } if (ViewerCountTextMesh != null) { ViewerCountTextMesh.text = string.Format("Viewers: {0}", obj.stream.viewers); } } else { ClearViewerCountAndChannelName(); } } else { ClearViewerCountAndChannelName(); } } } else { Debug.LogError("Error on page (" + url + "): " + www.error); } yield return(new WaitForSeconds(10f)); } }
// TEST ------------------------------------------------------ // IEnumerator GetDataclientFromDb () // { //// WWWForm form = new WWWForm(); //// form.AddField("Mail",); // WWW itemsData = new WWW ("http://togeathosting.altervista.org/QueryGetDataRiepBollette.php"); // yield return itemsData; // string itemsDataString = itemsData.text; // items = itemsDataString.Split (';'); // // prendo i dati in modo corretto ma pensare come fare check, una è una coroutine e non è sincronizzata // // scandisco tutti i nomi delle mail e delle pass e controllo se almeno una fa check // for (int i = 0; i < items.Length -1; i++ ){ // string[] mailAndPass = items[i].Split('|'); // Debug.LogError("i: " + i + " item: " + items[i].ToString()); //// string[] mailTotal = mailAndPass[0].Split (':'); //// string[] passTotal = mailAndPass[1].Split (':'); // } // } // utilizzare per checcare e poi andare a settare i valori al client IEnumerator GetAndSendDataToClient(string mail) { WWWForm form = new WWWForm(); form.AddField("mailclientPost", mail); WWW itemsData = new WWW("http://togeathosting.altervista.org/QueryGetDataRiepBollette.php"); yield return(itemsData); string itemsDataString = itemsData.text; items = itemsDataString.Split(';'); // prendo i dati in modo corretto ma pensare come fare check, una è una coroutine e non è sincronizzata // scandisco tutti i nomi delle mail e delle pass e controllo se almeno una fa check for (int i = 0; i < items.Length - 1; i++) { getItemVector = items[i].Split('|'); dataClient = new DataClient(); for (int j = 0; j < getItemVector.Length; j++) { testString = getItemVector[j].Split(':'); switch (j) { case 0: dataClient.nome = testString [1]; break; case 1: dataClient.pod = testString [1]; break; case 2: dataClient.nFtt = testString [1]; break; case 3: dataClient.emissione = testString [1]; break; case 4: dataClient.perRifIn = testString [1]; break; case 5: dataClient.perRifFine = testString [1]; break; case 6: dataClient.origineDati = testString [1]; break; case 7: dataClient.f1 = 2; break; case 8: dataClient.f2 = 2; break; case 9: dataClient.f3 = 2; break; } } TargetSetDataClient(connectionToClient, dataClient); } TargetChekValue(connectionToClient, true); }
IEnumerator GetCharacterOnDungeon() { string myUserId = AstaPageManager.Instance.idUser; WWWForm form = new WWWForm(); form.AddField("idDungeon", myId); form.AddField("idUser", myUserId); WWW itemsData = new WWW("http://astaapp.altervista.org/GetCharacterOnDungeon.php", form); yield return(itemsData); string itemsDataString = itemsData.text; Debug.Log("0 ReturnDB: " + itemsDataString); try { string[] itemsCharacterOnDungeonArray = itemsDataString.Split(';'); string[] itemSplit = itemsCharacterOnDungeonArray[0].ToString().Split('@'); //Debug.Log("Item0: " + itemSplit[0] + " item1: " + itemSplit[1] + " item2: " + itemSplit[2] + " item2: " + itemSplit[3] ); if (string.Compare(itemSplit[0], "FREE") == 0) // Controllo se mi ritorna un valore già terminato su DB o no { int characterId = int.Parse(itemSplit[1]); // Lasciarlo libero e assegnargli bonus o malus finito dungeon GameObject[] listCharacters = GameObject.FindGameObjectsWithTag("Character"); for (int i = 0; i < listCharacters.Length; i++) { string[] nameSplit = listCharacters[i].name.Split('.'); int idCharacterObj = int.Parse(nameSplit[1]); if (idCharacterObj == characterId) { listCharacters[i].GetComponent <AstaDungeonCharacterSelectedObj>().LifeValue -= int.Parse(itemSplit[3]); // caso con tempo finito e gli assegno malus o bonus // Aggiungere denaro //sbloccare character e aggiornare vita su DB if (listCharacters[i].GetComponent <AstaDungeonCharacterSelectedObj>().LifeValue <= 0) { AstaPageManager.Instance.DeleteCharacterUser(listCharacters[i].GetComponent <AstaDungeonCharacterSelectedObj>().myId); Destroy(listCharacters[i]); // Qua eliminare da DB } } } } else // caso ancora occupato { Debug.Log("DEVO stampare la data"); int characterId = int.Parse(itemSplit[1]); // num characters DB SetCharacterOnSlot(characterId); List <AstaPageManager.Character> listUserCHR = AstaPageManager.Instance.listUserCharacters; for (int i = 0; i < listUserCHR.Count; i++) { Debug.Log("confronto idList: " + listUserCHR[i].id + " conIDDB: " + characterId); if (listUserCHR[i].id == characterId) { Debug.Log("data: " + listUserCHR[i].dateEndTime); endOfOccupedDateCharacterInSLot = listUserCHR[i].dateEndTime; } } } } catch (Exception e) { Debug.Log("Nessun id da assegnare al Dungeon"); } }