示例#1
1
    IEnumerator Get(string url, int kindinfo)
    {
        WWW www = new WWW (url);
        yield return www;

        var jsonData = Json.Deserialize(www.text) as Dictionary<string,object>;

        switch (kindinfo) {
        case 1:
            state_parse(jsonData);
            break;
        case 2:
            users_parse(jsonData);
            break;
        case 3:
            play_parse(jsonData);
            break;
        case 4:
            winner_parse(jsonData);
            break;
        case 5:
            piece_parse(jsonData);
            break;
        default:
            break;
        }
    }
    IEnumerator SendCreateRequest(string url)
    {
        WWW page = new WWW(url);
        yield return page;

        // Create an IList of all of the businesses returned to me.
        Dictionary<string, object> createSuccess = Json.Deserialize(page.text) as Dictionary<string, object>;

        if ((bool)createSuccess["s"])
        {
            _view.View.TriggerEvent("CreateSuccess");
            _eventManager.RepopulateEvents();
            NativeDialogs.Instance.ShowMessageBox("Success!", "Event successfully created!",
                new string[] { "OK" }, false, (string button) =>
                {
                });
        }
        else
        {
            Debug.Log("There was an error: " + createSuccess["reason"].ToString());
            NativeDialogs.Instance.ShowMessageBox("Error!", createSuccess["reason"].ToString(),
                new string[] { "OK" }, false, (string button) =>
                {
                });
        }
    }
示例#3
0
    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);
        }
    }
示例#4
0
	public void updateVotes(){
		
		if(voteCanvas.activeInHierarchy == true)
		{
			Debug.Log("updating...");


			WWW voteCount1 = new WWW (voteCount); 

			WWW voteCount22 = new WWW (voteCount2); 

			WWW voteCount33 = new WWW (voteCount3); 

			WWW countTotal1 = new WWW (countTotalUsers); 

			StartCoroutine(countVotes(voteCount1));

			StartCoroutine(countVotes2(voteCount22));

			StartCoroutine(countVotes3(voteCount33));

			StartCoroutine(countTotalCoroutine(countTotal1));

		}

		
	}
示例#5
0
    void OnCollisionEnter( Collision coll )
    {
        Letras2 letrasScript = Camera.main.GetComponent<Letras2>();

        // GameObject cambiacolorGO = GameObject.Find("Cambiacolor");
        // cambiacolorGT = cambiacolorGO.GetComponent<GUIText>();

        GameObject collidedWith = coll.gameObject;

        //cuando letra falsa choca con el pulpo, llama la funcion de matar todas las letras en la class ApplePicker2(limpiar todas las letras y elimina un corazon)
        if ( collidedWith.tag == "Incorrecto"){

            ApplePicker2 apScript = Camera.main.GetComponent<ApplePicker2>();
            // Call the public AppleDestroyed() method of apScript
            apScript.IncorrectoDestroyed();

        }

        //*cuando letra correcta choca con el pulpo, seguimos pensando...
        else if (collidedWith.tag == "Yes") {
            Destroy (collidedWith);
            letrasScript.success = true;

            string url = "http://*****:*****@gmail.com&&nameactor=alexiunity";
            // Asignamos la url del Servidor servernodejs y las variables que se enviaran a traves del metodo GET al Servidor xAPI
            WWW www = new WWW(url);
            StartCoroutine(WaitForRequest(www));

            Application.LoadLevel ("_Escenariofinal"); // al cumplir la condicion de aprobación se lee el escenario final
            // de esta forma hacemos el llamado de la funcion XAPI y envio de datos que se cargaran dentro del Badge
        }
    }
示例#6
0
    IEnumerator GetJSONData()
    {
        WWW www = new WWW("http://stag-dcsan.dotcloud.com/shop/items/powerup");

        float elapsedTime = 0.0f;

        while (!www.isDone) {

          elapsedTime += Time.deltaTime;

          if (elapsedTime >= 20.0f) break;

          yield return null;

        }

        if (!www.isDone || !string.IsNullOrEmpty(www.error)) {

          Debug.LogError(string.Format("Fail Whale!\n{0}", www.error));

          yield break;

        }

        string response = www.text;

        Debug.Log(elapsedTime + " : " + response);

           _data = (IList) Json.Deserialize(response);
        IDictionary item = (IDictionary) _data[_dataIndex];

        LoadData ();
        //UILabel DetailLabel = GameObject.Find("DetailLabel").GetComponent<UILabel>();
        //DetailLabel.text = item["description"].ToString();
    }
	//https://www.google.com/maps/views/view/streetview/fernando-de-noronha/mirante-1/-dqeDyeJ_jVbfMxRF6jUJw?gl=us&heading=301&pitch=80&fovy=90
	//http://maps.googleapis.com/maps/api/streetview?size=400x400&location=40.720032,%20-73.988354&fov=90&heading=255&pitch=11&sensor=false
	IEnumerator GoogleStreetViewTexture(double _lat, double _lon, double _heading, double _pitch = 0.0)
	{
        string url = "http://maps.googleapis.com/maps/api/streetview?"
            + "size=" + width + "x" + height
            + "&location=" + _lat + "," + _lon
            + "&heading=" + (_heading + sideHeading) % 360.0
            + "&pitch=" + (_pitch + sidePitch) % 360.0
            + "&fov=" + (fov)
            + "&sensor=false";

		if(key != "")
		{
			url += "&key=" + key;
		}

		WWW www = new WWW(url);
		yield return www;
		if(!string.IsNullOrEmpty(www.error))
			Debug.Log("Panorama " + name + ": " + www.error);
		else
			print ("Panorama " + name + " loaded url " + url);


		renderer.material.mainTexture = www.texture;

        if(saveTextureFileName != "")
        {
            string realSavePath = Application.persistentDataPath + "/" + saveTextureFileName + ".png";
            Debug.Log("Encode Texture : " + realSavePath);

            byte[] png = www.texture.EncodeToPNG();
            File.WriteAllBytes(realSavePath, png);
        }
	}
示例#8
0
文件: Begin.cs 项目: QinFangbi/hugula
 private IEnumerator CompareAndroidVersion()
 {
     ReadPersistentVersion();
     string path = Application.streamingAssetsPath + "/" + VERSION_FILE_NAME;
     WWW www = new WWW(path);
     yield return www;
     this.streamingVersion = int.Parse(www.text.Trim());
     Debug.Log(string.Format(" persistentVersion= {0},streamingVersion = {1}", this.persistentVersion, this.streamingVersion));
     if (this.persistentVersion < this.streamingVersion)// copy streaming to persistent
     {
         string fileName = Application.streamingAssetsPath + "/data.zip";//  --System.IO.Path.ChangeExtension(Application.streamingAssetsPath,".zip");
         CRequest req = new CRequest(fileName);
         req.OnComplete += delegate(CRequest r)
         {
             byte[] bytes = null;
             if (r.data is WWW)
             {
                 WWW www1 = r.data as WWW;
                 bytes = www1.bytes;
             }
             FileHelper.UnZipFile(bytes, Application.persistentDataPath);
             LuaBegin();
         };
         this.multipleLoader.LoadReq(req);
     }
     else
     {
         LuaBegin();
     }
 }
	/// <summary>
	/// 
	/// </summary>
	public static void Create(string assetCode, string localVersion)
	{

		m_InfoReady = false;
		m_LatestVersion = null;

		m_AssetCode = assetCode;
		m_LocalVersion = localVersion;

		vp_UpdateDialog window = (vp_UpdateDialog)EditorWindow.GetWindow(typeof(vp_UpdateDialog), true);

		window.titleContent.text = "Check for Updates";
		window.minSize = new Vector2(m_DialogSize.x, m_DialogSize.y);
		window.maxSize = new Vector2(m_DialogSize.x, m_DialogSize.y);
		window.position = new Rect(
			(Screen.currentResolution.width / 2) - (m_DialogSize.x / 2),
			(Screen.currentResolution.height / 2) - (m_DialogSize.y / 2),
			m_DialogSize.x,
			m_DialogSize.y);
		window.Show();

		window.m_Icon = m_UFPSIcon;

		m_ReleaseNotesPath = "http://www.visionpunk.com/hub/assets/" + m_AssetCode + "/releasenotes";

		m_InfoFile = new WWW("http://www.visionpunk.com/content/assets/" + m_AssetCode + "/info.txt");
		
	}
 /// <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);
     }
 }
示例#11
0
    //POST请求(Form表单传值、效率低、安全 ,)  
    IEnumerator POST(string url, Dictionary<string, string> post)
    {
        //表单   
        WWWForm form = new WWWForm();
        //从集合中取出所有参数,设置表单参数(AddField()).  
        foreach (KeyValuePair<string, string> post_arg in post)
        {
            form.AddField(post_arg.Key, post_arg.Value);
        }
        //表单传值,就是post   
        WWW www = new WWW(url, form);

        yield return www;
        mJindu = www.progress;

        if (www.error != null)
        {
            //POST请求失败  
            mContent = "error :" + www.error;
        }
        else
        {
            //POST请求成功  
            mContent = www.text;
        }
    }
示例#12
0
    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 = "";
    }
    public void LogScreen(string title)
    {
        title = WWW.EscapeURL(title);

        var url = "http://www.google-analytics.com/collect?v=1&ul=en-us&t=appview&sr="+screenRes+"&an="+WWW.EscapeURL(appName)+"&a=448166238&tid="+propertyID+"&aid="+bundleID+"&cid="+WWW.EscapeURL(clientID)+"&_u=.sB&av="+appVersion+"&_v=ma1b3&cd="+title+"&qt=2500&z=185";

        WWW request = new WWW(url);

        /*if(request.error == null)
        {
            if (request.responseHeaders.ContainsKey("STATUS"))
            {
                if (request.responseHeaders["STATUS"] == "HTTP/1.1 200 OK")
                {
                    Debug.Log ("GA Success");
                }else{
                    Debug.LogWarning(request.responseHeaders["STATUS"]);
                }
            }else{
                Debug.LogWarning("Event failed to send to Google");
            }
        }else{
            Debug.LogWarning(request.error.ToString());
        }*/
    }
    public IEnumerator LoadLevelBundle(string levelName, string url, int version)
    {
        //		WWW download;
        //		download = WWW.LoadFromCacheOrDownload( url, version );

        WWW download;
        if ( Caching.enabled ) {
            while (!Caching.ready)
                yield return null;
            download = WWW.LoadFromCacheOrDownload( url, version );
        }
        else {
            download = new WWW (url);
        }

        //		WWW download = new WWW(url);
        //
        yield return download;
        if ( download.error != null ) {
            Debug.LogError( download.error );
            download.Dispose();
            yield break;
        }

        AssetBundle assetBundle = download.assetBundle;
        download.Dispose();
        download = null;

        if (assetBundle.LoadAllAssets() != null)
            Application.LoadLevel(levelName);

        assetBundle.Unload(false);
    }
示例#15
0
    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);
        }
    }
示例#16
0
	private void OnImageDownloaded(WWW www)
	{
		if (www.texture != null && previewTexture != null)
		{
			previewTexture.mainTexture = www.texture;
		}
	}
示例#17
0
 IEnumerator save_answer()
 {
     string urlMessage = "https://ilearn-td.herokuapp.com/api/records/save_answer";
     WWWForm form = new WWWForm ();
     // pass the email authentication
     string user_email = ButtonLogin.user_email;
     form.AddField ("email", user_email);
     form.AddField ("quiz", 1);
     form.AddField ("question", "In what form does light travel?");
     form.AddField ("answer", chosenSolution);
     if (rightAnswer) {
         form.AddField ("correct", 1);
     }
     else
     {
         form.AddField("correct", 0);
     }
     WWW w = new WWW(urlMessage, form);
     yield return w;
     if (!string.IsNullOrEmpty (w.error))
     {
         // this is done if the authentication is rejected or the response has
         // value >= 400 which means error in authentication or connection or server is down
         Debug.Log("The record is not saved");
     }
     else
     {
         // if the response has OK status
     }
 }
示例#18
0
    public IEnumerator GetAd(int id)
    {
		BusinessCard = null;
        adReady = false;
        hasAd = false;
        BusinessID = id;
        string adURL = serverURL + "getAd?b=" + id;
        string bcURL = serverURL + "bizcard?id=" + id;

        WWW card = new WWW(bcURL);
        yield return card;
        BusinessCard = new Texture2D(Convert.ToInt32(card.texture.width),
                              Convert.ToInt32(card.texture.height),
                              TextureFormat.ARGB32, false);
        BusinessCard.SetPixels(card.texture.GetPixels());
        BusinessCard.Apply();

        WWW page = new WWW(adURL);
        yield return page;
        if (page.error == null && page.text[0] == '{')
        {
            Debug.Log(page.text);
            // Get the ad as a Dictionary object.
            hasAd = true;
            Dictionary<string, object> ad = Json.Deserialize(page.text) as Dictionary<string, object>;
            AdImages(ad);
            AdInfo = new AdData(ad);
        }

        adReady = true;
    }
示例#19
0
	private IEnumerator ExecuteLoginRequest(WWW www)
	{
		Debug.Log ("in exec");
		yield return www;
		if (www.error == null)
		{
			if(www.text.Contains("user exists"))
			{
				success_fail = 2;
				Debug.Log(success_fail);
			}
			if(www.text.Contains("user does not exist"))
			{
				success_fail = 1;
				Debug.Log(success_fail);
			}
			if(www.text.Contains("user already logged in"))
			{
				success_fail = 3;
				Debug.Log(success_fail);
			}
			if(www.text.Contains("database query failure"))
			{
				success_fail = 4;
				Debug.Log(success_fail);
			}
		} 
		else {
			success_fail = 0;
			Debug.Log("www error"+success_fail);
		}
		Debug.Log ("out exec");
	}
示例#20
0
    public IEnumerator WaitForRequest()
    {
        //  yield return new WaitForEndOfFrame();
        WWWForm form = new WWWForm();
            form.AddField("username", Id.name);
            form.AddField("wheatbought", f.aaa);
            form.AddField("dogsbought", 3);
            form.AddField("timeplayed", 4);
            form.AddField("timeplayedlvl1", 5);
            form.AddField("timeplayedlvl2", 6);
            form.AddField("timeplayedlvl3", 7);
            form.AddField("deathsinlvl1", 8);
            form.AddField("deathsinlvl2", 9);
            form.AddField("deathsinlvl3", 10);
            form.AddField("sheepkilledinlvl1", 11);
            form.AddField("sheepkilledinlvl2", 12);
            form.AddField("sheepkilledinlvl3", 13);
            form.AddField("score", 14);
            www = new WWW(url, form);
            yield return www;

        if (!string.IsNullOrEmpty(www.error))
        {
            print(www.error);
        }
        else
        {
            print("Finished Uploading scores");
        }
    }
	public void ClickOK()
	{     

		string nhamang_ = "VTE";//viettem
        if (networkType == 1) nhamang_ = "VNP";//vinaphone
        else if (networkType == 2) nhamang_ = "VMS";//mobile phone

		int c = Nap (nhamang_,l1_mathe.text,l2_seri.text);
        //Debug.Log("aaaaaaaaaaaaa: " + l1_mathe.text + l2_seri.text);
		int gem_add = c;
		switch (c)
		{

			case 10000: gem_add = 150; break;
			case 20000: gem_add = 350; break;
			case 50000: gem_add = 850; break;
			case 100000: gem_add = 1700; break;
			case 200000: gem_add = 3400; break;
            case 500000:gem_add = 10000; break;
			case -1: gem_add = 0; break;
			default: gem_add = 0;break;
		}

		if (gem_add > 0) 
		{
            WWW www1 = new WWW("http://gamethuanviet.com/duoi_hinh_bat_chu/UpdateCard.php?username="******"&card=" + c.ToString());//here
            ScoreControl.mScore += gem_add;           
            ScoreControl.saveGame();
            LabelNotice.text = "Bạn đã nhận " + gem_add.ToString() + " Xu";
		}

	}
 public IEnumerator KongParse(string s)
 {
     var q = ParseQueryString(s);
     string name = q.Get("kongregate_username");
     string id = q.Get("kongregate_user_id");
     if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(id) && id != "0")
     {
         userId = id;
         _Loader.vkPassword = id;
         userName = name;
         Debug.LogWarning(userId);
         Debug.LogWarning(userName);
         if (string.IsNullOrEmpty(_Loader.playerName))
             _Loader.playerName = name;
         site= Site.Kg;
         ExternalEval(@"kongregateAPI.loadAPI();");
         vkLoggedIn = true;
         var url = "http://www.kongregate.com/api/user_info.json?user_id=" + userId;
         Debug.LogWarning(url);
         var w = new WWW(url);
         yield return w;
         if (!string.IsNullOrEmpty(w.error))
             Debug.LogWarning(w.url + w.error);
         else
         {
             var data = JsonMapper.ToObject(w.text);
             _Loader.avatarUrl = data["avatar_url"].ToString();
             Debug.LogWarning("avatar " + _Loader.avatarUrl);
         }
     }
 }
示例#23
0
    private IEnumerator DownLoadImage()
    {
        WWW www = new WWW(iconUrl);
        yield return www;

        image.renderer.material.mainTexture = www.texture as Texture;
    }
    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));
        }
    }
    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;
            }
        }
    }
	IEnumerator WebService(string URL)
	{
		this.state = State.WaitingForResponse;

		WWW www = new WWW(URL);
		yield return www;

		if (www.error != "" && www.error != null)
		{
			this.state = State.ERROR;
		}
		else {
			string s = www.text;
			if (s.Contains("|"))
			{
				string[] values = s.Split(new char[] {'|'});
				if (values[0] == "ERROR")
				{
					this.state = State.ERROR;
					this.error = values[1];
				} 
				else if (values[0] == "OK")
				{
					this.state = State.OK;
					if (values.Length > 1) this.value = values[1];
				}
			}
		}
	}
    /**
     * Requires that sensorURL has been set
     * Initializes the sensor display module
     * Starts the value updating function (coroutine);
     */
    public IEnumerator Initialize(string URL)
    {
        // Parse URL
        WWW www = new WWW (URL);
        yield return www;
        url = URL;
        JSONClass node = (JSONClass)JSON.Parse (www.text);

        www = new WWW (node["property"]);
        yield return www;
        JSONNode propertyNode = JSON.Parse (www.text);

        resourceProperty = propertyNode ["name"];
        resourceType = myResource.resourceType;
        sensorType = mySensor.sensorType;
        urlDataPoint = url + "value/";

        // Set Base values (name, icon, refreshTime)
        SetIcon ();
        SetName ();

        // Starts UpdateSensorValue coroutine
        StartCoroutine ("UpdateSensorValue");

        yield return null;
    }
示例#28
0
    private IEnumerator RequestWWW(string url, byte[] data, Dictionary<string, string> headers, 
		Action<CNetResponse> complete, Action<string> error)
    {
        var www = new WWW(url, data, headers);
        var responseTime = 10f;
        while (www.isDone && responseTime > 0f)
        {
            responseTime -= Time.deltaTime;
            yield return m_Waiting;
        }
        if (responseTime < 0f)
        {
            error("Request time out");
            yield break;
        }
        yield return www;
        var response = new CNetResponse();
        response.www = www;
        if (www.bytes.Length > 0)
        {
            complete(response);
        }
        else
        {
            error(www.error);
        }
    }
示例#29
0
    protected IEnumerator StartStream()
    {
        //KEEP IT HERE
        string sexVideo = "file://" + Application.streamingAssetsPath + "/Sex1.ogv";
        string platonicVideo = "file://" + Application.streamingAssetsPath + "/Prude1.ogv";
        string url;

        if (isSexVideoPlaying)
        {
            url = sexVideo;
        }
        else
        {
            url = platonicVideo;
        }

        WWW videoStreamer = new WWW(url);

        movieTexture = videoStreamer.movie;
        GetComponent<AudioSource>().clip = movieTexture.audioClip;
        while (!movieTexture.isReadyToPlay)
        {
            yield return 0;
        }

        GetComponent<AudioSource>().Play ();
        movieTexture.Play ();
        movieTexture.loop = true;
        GetComponent<RawImage>().texture = movieTexture;
        //GetComponent<Renderer>().material.mainTexture = movieTexture;
    }
示例#30
0
    //-------------------------FOR PATCHING -----------------------------------------------------
    IEnumerator CheckForUpdates()
    {    //for the patcher. Check the version first. 
        buildVersion = "1.0";
        updating = true;
        showUpdateButton = false;
        updateMsg = "\n\n\nChecking For Updates..."; //GUI update for user
        yield return new WaitForSeconds(1.0f);                        //make it visible
        updateMsg = "\n\n\nEstablishing Connection...";//GUI update for user
        WWW patchwww = new WWW(url); //create new web connection to the build number site
        yield return patchwww;     // wait for download to finish
        var updateVersion = (patchwww.text).Trim();
        Debug.Log(updateVersion);

        if (updateVersion == buildVersion) //check version
        {    
            updateMsg = "\nCurrently update to date.";
            yield return new WaitForSeconds(1.0f);
            updating = false;
            showGUI = true;
            Debug.Log("No Update Avalible");
            GetComponent<MainMenu>().enabled = true;
        }
        else
        {
            patch = patchwww.text;
            updateMsg = "Update Available.\n\n Current Version: " + buildVersion + "\n Patch Version: " + patchwww.text + "\n\n Would you like to download updates?\n\nThis will close this program and \n will launch the patching program.";
            showUpdateButton = true;
            Debug.Log("Update Avalible");
        }
    }
    void DisplayStep(Step step)
    {
        // Get rid of leftovers from older steps
        foreach (Transform child in Display.transform)
        {
            GameObject.Destroy(child.gameObject);
        }

        // Change step name & number
        stepName.text   = step.Name;
        stepNumber.text = "step " + currentStep.ToString();

        displayText  = step.DisplayAnchoredText;
        displayImage = step.DisplayAnchoredImage;

        featObjects = step.FeatureAnchoredObjects;

        timer = timeDelayForMultipleObjects;

        textList = new List <Text>();

        foreach (DisplayAnchoredText entry in displayText)
        {
            double[] position = entry.Position.ToArray();
            float    scale    = entry.Scale;

            Vector3 pos             = new Vector3((float)position[0], (float)position[1], (float)position[2]);
            Text    newTextInstance = MonoBehaviour.Instantiate(DisplayTextFab) as Text;
            newTextInstance.transform.SetParent(Display.transform);
            newTextInstance.transform.localPosition = pos;
            newTextInstance.transform.localRotation = Quaternion.identity;
            if (scale > 0)
            {
                newTextInstance.transform.localScale = Vector3.Scale(newTextInstance.transform.localScale, new Vector3(scale, scale, 1));
            }

            textList.Add(newTextInstance);
            newTextInstance.text = entry.Text;
            newTextInstance.gameObject.SetActive(true);
        }
        currentTexttoBeDisplayed = textList.Count - 1;
        imageList = new List <Image>();

        foreach (DisplayAnchoredImage myImg in displayImage)
        {
            if (myImg.Image_Path == "")
            {
                continue;
            }
            double[] position = myImg.Position.ToArray();
            float    scale    = myImg.Scale;

            Vector3 pos = new Vector3((float)position[0], (float)position[1], (float)position[2]);
            //Create new UI image object for use
            Image newImgInstance = MonoBehaviour.Instantiate(DisplayImgFab) as Image;
            newImgInstance.transform.SetParent(Display.transform);
            newImgInstance.transform.localPosition = pos;
            newImgInstance.transform.localRotation = Quaternion.identity;


            imageList.Add(newImgInstance);

            var tex = new Texture2D(512, 512);

            string filePath = Application.streamingAssetsPath + "/Resources/" + jsonResourcesPath + myImg.Image_Path;

            // Code to deal with android compatibility
            if (filePath.Contains("://"))      // When in android
            {
                WWW www = new WWW(filePath);
                //yield return www;
                while (!www.isDone)
                {
                }

                tex.LoadImage(www.bytes);
            }
            else                         // When not in android
            {
                tex.LoadImage(File.ReadAllBytes(filePath));
            }


            if (tex == null)
            {
                Debug.Log(myImg.Image_Path + " not loaded properly");
            }
            newImgInstance.sprite = Sprite.Create((tex as Texture2D), new Rect(0.0f, 0.0f, tex.width, tex.height), new Vector2(0, 0), 100);
            int width  = newImgInstance.sprite.texture.width;
            int height = newImgInstance.sprite.texture.height;
            newImgInstance.transform.localScale = Vector3.Scale(newImgInstance.transform.localScale, new Vector3((float)width / height, 1, 1));
            if (scale > 0)
            {
                newImgInstance.transform.localScale = Vector3.Scale(newImgInstance.transform.localScale, new Vector3(scale, scale, 1));
            }
            newImgInstance.gameObject.SetActive(true);
        }
        currentImagetoBeDisplayed = imageList.Count - 1;

        //Clears pre-existing Marker objects before creating new ones
        foreach (Transform child in Marker.transform)
        {
            GameObject.Destroy(child.gameObject);
        }

        foreach (FeatureAnchoredObject feat in featObjects)
        {
            double[] position = feat.Position.ToArray();
            Vector3  pos      = new Vector3((float)position[0], (float)position[1], (float)position[2]);
            if (feat.Image_Path.ToLower().Equals("point"))
            {
                GameObject featureInstance = MonoBehaviour.Instantiate(PointFab);
                featureInstance.transform.SetParent(Marker.transform);
                featureInstance.transform.localPosition = pos;
                featureInstance.transform.localScale    = new Vector3(1, 1, 1);
                //featureInstance.layer = LayerMask.NameToLayer( "AR foreground" );
            }
        }
    }
示例#32
0
文件: SelectDB.cs 项目: Gibom/Unity3D
    //type (1 : 별 위치 , 2 : 플레이어 정보, 3 : )
    public void Select(int type)
    {

#if UNITY_EDITOR
        m_ConnectionString = "URI=file:" + Application.streamingAssetsPath + "/" + m_SQLiteFileName;
        //m_ConnectionString = "URI=file:" + Application.dataPath + "/" + m_SQLiteFileName;
#else
            // check if file exists in Application.persistentDataPath
            var filepath = string.Format("{0}/{1}", Application.persistentDataPath, m_SQLiteFileName);

            if (!File.Exists(filepath))
            {
                // if it doesn't ->
                // open StreamingAssets directory and load the db ->

#if UNITY_ANDROID
                WWW loadDb = new WWW("jar:file://" + Application.dataPath + "!/assets/" + m_SQLiteFileName);  // this is the path to your StreamingAssets in android
                loadDb.bytesDownloaded.ToString();
                while (!loadDb.isDone) { }  // CAREFUL here, for safety reasons you shouldn't let this while loop unattended, place a timer and error check
                // then save to Application.persistentDataPath
                File.WriteAllBytes(filepath, loadDb.bytes);
#elif UNITY_IOS
                     var loadDb = Application.dataPath + "/Raw/" + m_SQLiteFileName;  // this is the path to your StreamingAssets in iOS
                    // then save to Application.persistentDataPath
                    File.Copy(loadDb, filepath);
#elif UNITY_WP8
                    var loadDb = Application.dataPath + "/StreamingAssets/" + m_SQLiteFileName;  // this is the path to your StreamingAssets in iOS
                    // then save to Application.persistentDataPath
                    File.Copy(loadDb, filepath);
#elif UNITY_WINRT
      var loadDb = Application.dataPath + "/StreamingAssets/" + m_SQLiteFileName;  // this is the path to your StreamingAssets in iOS
      // then save to Application.persistentDataPath
      File.Copy(loadDb, filepath);
#else
     var loadDb = Application.dataPath + "/StreamingAssets/" + m_SQLiteFileName;  // this is the path to your StreamingAssets in iOS
     // then save to Application.persistentDataPath
     File.Copy(loadDb, filepath);

#endif
            }

            m_ConnectionString = "URI=file:" + filepath;
#endif

        /////////////////////////////////////////////////////////////////[DB Path]
        if (Application.platform == RuntimePlatform.Android)
        {
            conn = "URI=file:" + Application.persistentDataPath + "/CosmicDB.sqlite"; //Path to databse on Android
        }
        else
        {
            conn = "URI=file:" + Application.streamingAssetsPath + "/CosmicDB.sqlite";
        } //Path to database Else
          /////////////////////////////////////////////////////////////////[DB Path]
          //Debug.Log(conn);

        /////////////////////////////////////////////////////////////////[DB Connection]
        IDbConnection dbconn;
        dbconn = (IDbConnection)new SqliteConnection(conn);
        dbconn.Open(); //Open connection to the database.
        /////////////////////////////////////////////////////////////////[DB Connection]

        /////////////////////////////////////////////////////////////////[SELECT Query]
        IDbCommand dbcmd = dbconn.CreateCommand();
        //string sqlCount = "SELECT Count(rowid) as Count " + "FROM zodiacTable";
        //dbcmd.CommandText = sqlCount;
        //IDataReader reader = dbcmd.ExecuteReader();
        //while (reader.Read())
        //{
        //    cntField = reader.GetInt32(0);
        //}
        //reader.Close();
        //reader = null;
        sqlQuery = "SELECT " + column + " FROM " + table + " " + where;
        Debug.Log(sqlQuery);
        dbcmd.CommandText = sqlQuery;
        IDataReader reader = dbcmd.ExecuteReader();
        /////////////////////////////////////////////////////////////////[SELECT Query]


        /////////////////////////////////////////////////////////////////[Data Read]
        if (type == 0) // Count
        {
            while (reader.Read())
            {
                if (table == "managePlanetTable")
                    planetCount = reader.GetInt32(0);
                else if (table == "zodiacTable")
                    starCount = reader.GetInt32(0);
            }
            reader.Close();
            reader = null;
        }

        if (type == 1) // 별 좌표 
        {
            while (reader.Read())
            {
                x = reader.GetFloat(0);
                y = reader.GetFloat(1);
                z = reader.GetFloat(2);
                if (reader.GetString(3) != null && reader.GetString(4) != null)
                {
                    starName = reader.GetString(3);
                    zodiacName = reader.GetString(4);
                }
                starPosition = new Vector3(x, y, z);
            }
            reader.Close();
            reader = null;

        }
        if (type == 2) // 유저 보유 식량
        {
            while (reader.Read())
            {
                food = reader.GetInt16(0);
                shipNum = reader.GetInt16(1);
            }
            reader.Close();
            reader = null;
        }
        if (type == 3) // 행성 로드
        {
            if (reader.Read())
            {
                planetIndex = reader.GetInt16(0);
                planetName = reader.GetString(1);
                planetSize = reader.GetInt16(2);
                planetColor = reader.GetInt16(3);
                planetMat = reader.GetInt16(4);
                x = reader.GetFloat(5);
                y = reader.GetFloat(6);
                z = reader.GetFloat(7);
                if (reader.IsDBNull(8) == false)
                {
                    tree1 = reader.GetInt16(8);
                    tree2 = reader.GetInt16(9);
                    tree3 = reader.GetInt16(10);
                    tree4 = reader.GetInt16(11);
                    tree5 = reader.GetInt16(12);
                    tree6 = reader.GetInt16(13);
                }
                starPosition = new Vector3(x, y, z);
            }
            else
            {
                planetIndex = 0;
            }
            //Select 결과가 없을 경우 예외처리 필요

            reader.Close();
            reader = null;
        }
        if (type == 4) // 별 정보 PlanetCollisionCheck line: 66 에서 사용 
        {
            while (reader.Read())
            {
                starRowid = reader.GetInt32(0);
                starOpen = reader.GetInt32(1);
                starFind = reader.GetInt32(2);
                starActive = reader.GetInt32(3);
                if(reader.IsDBNull(4) == false)
                {
                    zodiacID = reader.GetString(4);
                    zodiacName = reader.GetString(5);
                }
            }
            reader.Close();
            reader = null;
        }


        /////////////////////////////////////////////////////////////////[Data Read]


        /////////////////////////////////////////////////////////////////[UPDATE Query]
        //string UpdatesqlQuery = "UPDATE zodiacTable SET \"locationX\" =" + x + ", \"locationY\" = " + y + ", \"locationZ\" = " + z + " WHERE  \"zID\" = '" + zID + "'";

        //Debug.Log(UpdatesqlQuery);
        //dbcmd.CommandText = UpdatesqlQuery;
        //dbcmd.ExecuteNonQuery();
        /////////////////////////////////////////////////////////////////[UPDATE Query]

        dbcmd.Dispose();
        dbcmd = null;
        /////////////////////////////////////////////////////////////////[DB Connection Close]
        dbconn.Close();
        dbconn = null;
        /////////////////////////////////////////////////////////////////[DB Connection Close]

    }
示例#33
0
        /// <summary>
        /// 加载
        /// </summary>
        /// <returns></returns>
        private IEnumerator Load()
        {
            string path = "";

            path       += this.m_strPath;
            this.m_cWww = new WWW(path);

            for ( ; !this.m_cWww.isDone;)
            {
                this.m_fProgess = this.m_cWww.progress;
                yield return(new WaitForSeconds(0));
            }

            if (this.m_cWww.error != null)
            {
                Debug.Log(m_cWww.error);
                if (this.m_cErrorCallBack != null)
                {
                    this.m_cErrorCallBack(this.m_cWww.error, this);
                }
            }
            else
            {
                this.m_bComplete = true;
                this.m_fProgess  = 1;

                if (this.m_cCallBack != null)
                {
                    switch (this.m_eResType)
                    {
                    case RESOURCE_TYPE.WEB_ASSETBUNLDE:
                        this.m_cCallBack(this.m_strPath, this.m_cWww.assetBundle);
                        break;

                    case RESOURCE_TYPE.WEB_TEXTURE:
                        this.m_cCallBack(this.m_strPath, this.m_cWww.texture);
                        break;

                    case RESOURCE_TYPE.WEB_TEXT_BYTES:
                        this.m_cCallBack(this.m_strPath, this.m_cWww.bytes);
                        break;

                    case RESOURCE_TYPE.WEB_TEXT_STR:
                        this.m_cCallBack(this.m_strPath, this.m_cWww.text);
                        break;
                    }
                }
                if (this.m_bAutoSave)
                {
                    Uri tmpUri = new Uri(this.m_strPath);

                    string dataPath = Application.persistentDataPath + tmpUri.AbsolutePath;
                    if (!tmpUri.IsFile)
                    {
                        CFile.WriteAllBytes(dataPath, this.m_cWww.bytes, this.m_lUTime);
                    }
                }
            }

            this.m_cWww.Dispose();
            this.m_cWww = null;
        }
示例#34
0
 /// <summary>
 /// 销毁
 /// </summary>
 public void Destory()
 {
     this.m_cWww = null;
 }
示例#35
0
        internal static void MakeApiCall <TRequestType, TResultType>(string api, string apiEndpoint, TRequestType request, Action <TResultType> resultCallback, Action <EditorModels.PlayFabError> errorCallback)
        {
            var url = apiEndpoint + api;
            var req = JsonWrapper.SerializeObject(request, PlayFabEditorUtil.ApiSerializerStrategy);
            //Set headers
            var headers = new Dictionary <string, string>
            {
                { "Content-Type", "application/json" },
                { "X-ReportErrorAsSuccess", "true" },
                { "X-PlayFabSDK", string.Format("{0}_{1}", PlayFabEditorHelper.EDEX_NAME, PlayFabEditorHelper.EDEX_VERSION) }
            };


            if (api.Contains("/Server/") || api.Contains("/Admin/"))
            {
                if (PlayFabEditorDataService.activeTitle == null || string.IsNullOrEmpty(PlayFabEditorDataService.activeTitle.SecretKey))
                {
                    PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, "Must have PlayFabSettings.DeveloperSecretKey set to call this method");
                    return;
                }

                headers.Add("X-SecretKey", PlayFabEditorDataService.activeTitle.SecretKey);
            }



            //Encode Payload
            var payload = System.Text.Encoding.UTF8.GetBytes(req.Trim());

            var www = new WWW(url, payload, headers);

            PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnHttpReq, api, PlayFabEditorHelper.MSG_SPIN_BLOCK);

            EditorCoroutine.start(Post(www, (response) =>
            {
                var httpResult = JsonWrapper.DeserializeObject <HttpResponseObject>(response,
                                                                                    PlayFabEditorUtil.ApiSerializerStrategy);

                if (httpResult.code == 200)
                {
                    try
                    {
                        PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnHttpRes, api);

                        var dataJson = JsonWrapper.SerializeObject(httpResult.data,
                                                                   PlayFabEditorUtil.ApiSerializerStrategy);
                        var result = JsonWrapper.DeserializeObject <TResultType>(dataJson,
                                                                                 PlayFabEditorUtil.ApiSerializerStrategy);

                        if (resultCallback != null)
                        {
                            resultCallback(result);
                        }
                    }
                    catch (Exception e)
                    {
                        PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, e.Message);
                    }
                }
                else
                {
                    if (errorCallback != null)
                    {
                        PlayFab.Editor.EditorModels.PlayFabError playFabError = PlayFabEditorHelper.GeneratePlayFabError(response);
                        errorCallback(playFabError);
                    }
                    else
                    {
                        PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, string.Format("ErrorCode:{0} -- {1}", httpResult.code, httpResult.status));
                    }
                }
            }, (error) =>
            {
                if (errorCallback != null)
                {
                    var playFabError = PlayFabEditorHelper.GeneratePlayFabError(error);
                    errorCallback(playFabError);
                }
                else
                {
                    PlayFabEditor.RaiseStateUpdate(PlayFabEditor.EdExStates.OnError, error);
                }
            }), www);
        }
示例#36
0
    //------------Load Levels --------------------
    public static List <LevelData> LoadLevels()
    {
        List <LevelData> lvlsData  = new List <LevelData>();
        string           jsonData  = "";
        bool             isNetwork = Application.internetReachability != NetworkReachability.NotReachable;

        //Debug.Log(" >>>> is NEtwork " + isNetwork);
        if (Application.platform == RuntimePlatform.Android)
        {
            if (isNetwork)
            {
                WWW reader = new WWW(levelfilePath);
                while (!reader.isDone)
                {
                }

                jsonData = reader.text;

                //Save the file
                StreamWriter writer = new StreamWriter(levelfilePathLocal, false);
                writer.WriteLine(jsonData);
                writer.Close();
            }
            else
            {
                if (!File.Exists(levelfilePathLocal))
                {
                    TextAsset file = Resources.Load("levels") as TextAsset;
                    jsonData = file.ToString();
                }
                else
                {
                    jsonData = File.ReadAllText(levelfilePathLocal);
                }
                //TextAsset file = Resources.Load("levels.json") as TextAsset;
                //jsonData = file.ToString();
                //WWW reader = new WWW(levelfilePathLocal);
                //while (!reader.isDone) { }
                //jsonData = reader.text;
            }
        }
        else
        {
            if (isNetwork)
            {
                WWW reader = new WWW(levelfilePath);
                while (!reader.isDone)
                {
                }
                jsonData = reader.text;

                // Debug.Log(" >>>> levels jsonData " + jsonData);
                //Save the file
                StreamWriter writer = new StreamWriter(levelfilePathLocal, false);
                writer.WriteLine(jsonData);
                writer.Close();
            }
            else
            {
                jsonData =
                    File.ReadAllText(levelfilePathLocal);
            }
        }


        if (jsonData != null)
        {
            string   separ = "Level_[0-9][0-9][0-9]";
            string[] lvls  = System.Text.RegularExpressions.Regex.Split(jsonData, separ);

            for (int i = 1; i < lvls.Length; i++)
            {
                string editedLvl = "{ \"Rows" + lvls[i].Substring(1, lvls[i].Length - 7);
                if (editedLvl.LastIndexOf("]") == editedLvl.Length - 1)
                {
                    editedLvl += "}";
                }
                else
                {
                    editedLvl += "]}";
                }
                RowData[] rows    = JsonHelper.FromJson <RowData>(editedLvl);
                LevelData lvlData = new LevelData();
                System.Array.Reverse(rows);

                foreach (RowData row in rows)
                {
                    if (!row.IsEmpty())
                    {
                        lvlData.rows.Add(row);
                    }
                }

                foreach (RowData row in rows)
                {
                    if (row.IsEmpty())
                    {
                        lvlData.emptyRowsCount++;
                    }
                    else
                    {
                        break;
                    }
                }

                lvlsData.Add(lvlData);
            }
            return(lvlsData);
        }
        else
        {
            //Debug.LogError("Cannot find the file " + levelfilePath);
            //AjsonData = "<color=#a52a2aff>JSON IS NULL</color>";
            return(lvlsData);
        }
    }
示例#37
0
 private IEnumerator InvokeRequest(IUnityHttpRequest request)
 {
     if ((ServiceFactory.Instance.GetService <INetworkReachability>() as NetworkReachability).NetworkStatus != 0)
     {
         if (request is UnityWwwRequest)
         {
             WWW wwwRequest = new WWW((request as UnityWwwRequest).RequestUri.AbsoluteUri, request.RequestContent, request.Headers);
             if (wwwRequest == null)
             {
                 yield return((object)null);
             }
             bool uploadCompleted2 = false;
             while (!wwwRequest.get_isDone())
             {
                 float uploadProgress = wwwRequest.get_uploadProgress();
                 if (!uploadCompleted2)
                 {
                     request.OnUploadProgressChanged(uploadProgress);
                     if (uploadProgress == 1f)
                     {
                         uploadCompleted2 = true;
                     }
                 }
                 yield return((object)null);
             }
             request.WwwRequest = (IDisposable)wwwRequest;
             request.Response   = new UnityWebResponseData(wwwRequest);
         }
         else
         {
             UnityRequest unityRequest = request as UnityRequest;
             if (unityRequest == null)
             {
                 yield return((object)null);
             }
             UnityWebRequestWrapper unityWebRequest = new UnityWebRequestWrapper(unityRequest.RequestUri.AbsoluteUri, unityRequest.Method)
             {
                 DownloadHandler = new DownloadHandlerBufferWrapper()
             };
             if (request.RequestContent != null && request.RequestContent.Length != 0)
             {
                 unityWebRequest.UploadHandler = new UploadHandlerRawWrapper(request.RequestContent);
             }
             bool uploadCompleted = false;
             foreach (KeyValuePair <string, string> header in request.Headers)
             {
                 unityWebRequest.SetRequestHeader(header.Key, header.Value);
             }
             AsyncOperation operation = unityWebRequest.Send();
             while (!operation.get_isDone())
             {
                 float progress = operation.get_progress();
                 if (!uploadCompleted)
                 {
                     request.OnUploadProgressChanged(progress);
                     if (progress == 1f)
                     {
                         uploadCompleted = true;
                     }
                 }
                 yield return((object)null);
             }
             request.WwwRequest = unityWebRequest;
             request.Response   = new UnityWebResponseData(unityWebRequest);
         }
     }
     else
     {
         request.Exception = new WebException("Network Unavailable", WebExceptionStatus.ConnectFailure);
     }
     if (request.IsSync)
     {
         if (request.Response != null && !request.Response.IsSuccessStatusCode)
         {
             request.Exception = new HttpErrorResponseException(request.Response);
         }
         request.WaitHandle.Set();
     }
     else
     {
         if (request.Response != null && !request.Response.IsSuccessStatusCode)
         {
             request.Exception = new HttpErrorResponseException(request.Response);
         }
         ThreadPool.QueueUserWorkItem(delegate
         {
             try
             {
                 request.Callback(request.AsyncResult);
             }
             catch (Exception exception)
             {
                 _logger.Error(exception, "An exception was thrown from the callback method executed fromUnityMainThreadDispatcher.InvokeRequest method.");
             }
         });
     }
 }
示例#38
0
    IEnumerator LoginAccountFromServer(string email, string password)
    {
        WWWForm form1 = new WWWForm();

        form1.AddField("email", email);
        form1.AddField("password", password);

        WWW www = new WWW(loginaccounturl, form1);

        yield return(www);

        print("message came" + www.text);

        if (www.text == "Incorrect password")
        {
            statusText.text  = "Incorrect password";
            statusText.color = Color.red;
        }
        else if (www.text == "server error")
        {
            statusText.text  = "Server is in the maintainence";
            statusText.color = Color.red;
        }
        else if (www.text == "")
        {
            statusText.text  = "Check the connection";
            statusText.color = Color.red;
        }
        else
        {
            if (www.text.Contains("id:"))
            {
                //account created successfully

                statusText.text  = "Account created successfully";
                statusText.color = Color.green;


                //update name on the top
                //extracting username

                string username = GetDataValue(www.text, "username:"******"id:");
                int    idnumber   = Convert.ToInt32(idinstring);
                print(idnumber);
                saveload.id       = idnumber;
                saveload.username = username;
                saveload.email    = email;

                saveload.Save();

                ActivatePanel(HomepagePannel.name);
                UpdateTopDetails();
                EmailLoginInputText.text    = "";
                PasswordLoginInputText.text = "";
            }
            else
            {
                statusText.text  = "Server is in the maintainence";
                statusText.color = Color.red;
            }
        }
    }
示例#39
0
    /// <summary>
    /// 释放资源,把streamasset下的资源拷贝到平台对应的沙盒目录
    /// </summary>
    IEnumerator OnExtractResource()
    {
        string resPath  = Util.AppContentPath(); //游戏包资源目录
        string dataPath = Util.DataPath;         //数据目录

        if (Directory.Exists(dataPath))
        {
            Directory.Delete(dataPath, true);
        }

        Directory.CreateDirectory(dataPath);

        string infile  = resPath + versionTxtName;
        string outfile = dataPath + versionTxtName;

        if (File.Exists(outfile))
        {
            File.Delete(outfile);
        }

        string message = "正在解包文件:>" + versionTxtName;

        LogHelper.Log("infile:" + infile);
        LogHelper.Log("outfile:" + outfile);
        LogHelper.Log(message);

        //只有Android平台要流方式www,其它平台都可以IO方式
        if (Application.platform == RuntimePlatform.Android)
        {
            WWW www = new WWW(infile);
            yield return(www);

            if (www.isDone)
            {
                File.WriteAllBytes(outfile, www.bytes);
            }
            yield return(0);
        }
        else
        {
            File.Copy(infile, outfile, true);
        }

        yield return(new WaitForEndOfFrame());

        //释放所有文件到数据目录
        string[] files = File.ReadAllLines(outfile);
        foreach (var file in files)
        {
            string[] fs = file.Split('|');
            if (fs[0] == "Date") //第一行不处理
            {
                continue;
            }

            infile  = resPath + fs[0];
            outfile = dataPath + fs[0];

            message = "正在解包文件:>" + fs[0];
            LogHelper.Log("正在解包文件:>" + infile);

            string dir = Path.GetDirectoryName(outfile);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            if (Application.platform == RuntimePlatform.Android)
            {
                WWW www = new WWW(infile);
                yield return(www);

                if (www.isDone)
                {
                    File.WriteAllBytes(outfile, www.bytes);
                }
                yield return(0);
            }
            else
            {
                if (File.Exists(outfile))
                {
                    File.Delete(outfile);
                }
                File.Copy(infile, outfile, true);
            }
            yield return(new WaitForEndOfFrame());
        }
        message = "解包完成!!!";
        LogHelper.Log(message);

        yield return(new WaitForSeconds(0.1f));

        message = string.Empty;

        //释放完成,开始启动更新资源,先读取本地版本文件
        StartCoroutine(LoadLocalVersionData());
    }
    public IEnumerator loadTiles(int zoom)
    {
        int    size  = _settings.size;
        string key   = _settings.key;
        string style = _settings.style;

        lat = Input.location.lastData.latitude;
        lon = Input.location.lastData.longitude;
        //lat = oldLat + 0.0002f;
        //lon = oldLon + 0.0002f;


        string url = String.Format("https://api.mapbox.com/v4/mapbox.{5}/{0},{1},{2}/{3}x{3}@2x.png?access_token={4}", lon, lat, zoom, size, key, style);

        WWW www = new WWW(url);

        yield return(www);

        texture = www.texture;

        if (tile == null)
        {
            tile      = GameObject.CreatePrimitive(PrimitiveType.Plane);
            tile.name = "Tile " + lat + "" + lon;
            tile.transform.localScale = Vector3.one * _settings.scale;
            tile.GetComponent <Renderer>().material = _settings.material;
            tile.transform.parent = transform;
            tile.transform.Rotate(0, -90, 0);
        }

        if (oldLat != 0 && oldLon != 0)
        {
            float   x, y;
            Vector3 position = Vector3.zero;

            geodeticOffsetInv(lat * Mathf.Deg2Rad, lon * Mathf.Deg2Rad, oldLat * Mathf.Deg2Rad, oldLon * Mathf.Deg2Rad, out x, out y);

            if ((oldLat - lat) < 0 && (oldLon - lon) > 0 || (oldLat - lat) > 0 && (oldLon - lon) < 0)
            {
                position = new Vector3(x, 0.01f, y);
            }
            else
            {
                position = new Vector3(-x, 0.01f, -y);
            }

            position.x *= 0.030012f; //2
            position.z *= 0.012304f; //3

            target.position = position;

            /*float[] ll = px (lat, lon, _settings.zoom);
             *          float[] oll = px (oldLat, oldLon, _settings.zoom);
             *          x = ll [0] - oll [0];
             *          y = ll [0] - oll [0];
             *
             *          float ps = 10 * _settings.scale / _settings.size;
             *          x *= ps;
             *          y *= ps;
             *
             *          Debug.Log (x + " / " + y);*/
        }

        alienManager.UpdateAlienPosition();

        tile.GetComponent <Renderer>().material.mainTexture = texture;

        yield return(new WaitForSeconds(1f));

        oldLat = lat;
        oldLon = lon;

        while (oldLat == lat && oldLon == lon)
        {
            lat = Input.location.lastData.latitude;
            lon = Input.location.lastData.longitude;
            //lat = oldLat + 0.0002f;
            //lon = oldLon + 0.0002f;
            yield return(new WaitForSeconds(0.5f));
        }

        yield return(new WaitUntil(() => (oldLat != lat || oldLon != lon)));

        yield return(StartCoroutine(loadTiles(_settings.zoom)));

        yield break;
    }
示例#41
0
        //BtnMenu -> this has 3 possible types, "ShortcutMenu", "UserInteractMenu" or a QMNestedButton (button that opens up to other buttons)
        //ShortcutMenu -> main quick menu with worlds/avatars

        public static IEnumerator CreateButton(MenuType Menu, ButtonType type, string ButtonText, int X, int Y, UnityAction action, string buttonTooltip, Color color, Color BtnText, QMNestedButton MainButton = null, string SpriteImage = null, string OnText = null, string OffText = null, UnityAction OffAction = null, Color?BackButtonColor = null, Color?BackButtonTextColor = null)
        {
            string MenuString = "ShortcutMenu";

            switch (Menu)
            {
            default: MenuString = "ShortcutMenu"; break;

            case MenuType.ShortCut: MenuString = "ShortcutMenu"; break;

            case MenuType.UserInteract: MenuString = "UserInteractMenu"; break;

            case MenuType.UserInfo: MenuString = "UserInfo"; break;
            }

            switch (type)
            {
            default: break;

            case ButtonType.Single:
                QMSingleButton x = null;
                if (MainButton != null)
                {
                    x = new QMSingleButton(MainButton, X, Y, ButtonText, action, buttonTooltip, color, BtnText);
                }
                else
                {
                    x = new QMSingleButton(MenuString, X, Y, ButtonText, action, buttonTooltip, color, BtnText);
                }

                if (SpriteImage != null)
                {
                    var sprite = new Sprite();

                    using (WWW www = new WWW(SpriteImage))
                    {
                        yield return(www);

                        sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height),
                                               new Vector2(0, 0));
                    }

                    x.getGameObject().GetComponentInChildren <UnityEngine.UI.Image>().sprite = sprite;
                    Material logoMaterial = new Material(x.getGameObject().GetComponentInChildren <UnityEngine.UI.Image>().material);
                    logoMaterial.shader = Shader.Find("Unlit/Transparent");
                    x.getGameObject().GetComponentInChildren <UnityEngine.UI.Image>().material = logoMaterial;
                }
                UIHelper.ButtonOutput.Add(x);
                break;

            case ButtonType.Toggle:
                QMToggleButton y = null;
                if (MainButton != null)
                {
                    y = new QMToggleButton(MainButton, X, Y, OnText, action, OffText, OffAction, buttonTooltip, color, BtnText);
                }
                else
                {
                    y = new QMToggleButton(MenuString, X, Y, OnText, action, OffText, OffAction, buttonTooltip, color, BtnText);
                }


                if (SpriteImage != null)
                {
                    var sprite = new Sprite();

                    using (WWW www = new WWW(SpriteImage))
                    {
                        sprite = Sprite.Create(www.texture, new Rect(0, 0, www.texture.width, www.texture.height),
                                               new Vector2(0, 0));
                    }

                    y.getGameObject().GetComponentInChildren <UnityEngine.UI.Image>().sprite = sprite;
                    Material logoMaterial = new Material(y.getGameObject().GetComponentInChildren <UnityEngine.UI.Image>().material);
                    logoMaterial.shader = Shader.Find("Unlit/Transparent");
                    y.getGameObject().GetComponentInChildren <UnityEngine.UI.Image>().material = logoMaterial;
                }
                UIHelper.ButtonOutput.Add(y);
                break;

            case ButtonType.Nested:
                if (MainButton != null)
                {
                    var f = new QMNestedButton(MainButton, X, Y, ButtonText, buttonTooltip, color, BtnText, (Color)BackButtonColor, (Color)BackButtonTextColor);
                    UIHelper.ButtonOutput.Add(f);
                }
                else
                {
                    var z = new QMNestedButton(MenuString, X, Y, ButtonText, buttonTooltip, color, BtnText, (Color)BackButtonColor, (Color)BackButtonTextColor);
                    UIHelper.ButtonOutput.Add(z);
                }
                break;
            }
        }
示例#42
0
    IEnumerator CreateAccountFromServer(string username, string email, string password)
    {
        WWWForm form1 = new WWWForm();

        form1.AddField("username", username);
        form1.AddField("email", email);
        form1.AddField("password", password);

        WWW www = new WWW(createaccounturl, form1);

        yield return(www);

        print("message came" + www.text);


        if (www.text == "Account Already Exist")
        {
            statusText.text  = "Account alrady Exist";
            statusText.color = Color.red;
        }
        else if (www.text == "")
        {
            statusText.text  = "Check the connection";
            statusText.color = Color.red;
        }
        else if (www.text == "Connection Failed")
        {
            statusText.text  = "Server is in the maintainence";
            statusText.color = Color.red;
        }
        else
        {
            if (www.text.Contains("id:"))
            {
                //account created successfully

                statusText.text  = "Account created successfully";
                statusText.color = Color.green;


                //update name on the top
                int    temp       = www.text.IndexOf(":");
                string idinstring = www.text.Substring(temp + 1);
                int    idnumber   = Convert.ToInt32(idinstring);

                saveload.id       = idnumber;
                saveload.username = username;
                saveload.email    = email;

                saveload.Save();

                ActivatePanel(HomepagePannel.name);
                UpdateTopDetails();
            }
            else
            {
                statusText.text  = "Server is in the maintainence";
                statusText.color = Color.red;
            }
        }
    }
示例#43
0
    IEnumerator _Refresh()
    {
        var url = "http://maps.googleapis.com/maps/api/staticmap";
        var qs  = "";

        if (!autoLocateCenter)
        {
            if (centerLocation.address != "")
            {
                qs += "center=" + WWW.UnEscapeURL(centerLocation.address);
            }
            else
            {
                qs += "center=" + WWW.UnEscapeURL(string.Format("{0},{1}", centerLocation.latitude, centerLocation.longitude));
            }

            qs += "&zoom=" + zoom.ToString();
        }
        qs += "&size=" + WWW.UnEscapeURL(string.Format("{0}x{0}", size));
        qs += "&scale=" + (doubleResolution ? "2" : "1");
        qs += "&maptype=" + mapType.ToString().ToLower();
        var usingSensor = false;

#if UNITY_IPHONE
        usingSensor = Input.location.isEnabledByUser && Input.location.status == LocationServiceStatus.Running;
#endif
        qs += "&sensor=" + (usingSensor ? "true" : "false");

        foreach (var i in markers)
        {
            qs += "&markers=" + string.Format("size:{0}|color:{1}|label:{2}", i.size.ToString().ToLower(), i.color, i.label);
            foreach (var loc in i.locations)
            {
                if (loc.address != "")
                {
                    qs += "|" + WWW.UnEscapeURL(loc.address);
                }
                else
                {
                    qs += "|" + WWW.UnEscapeURL(string.Format("{0},{1}", loc.latitude, loc.longitude));
                }
            }
        }

        foreach (var i in paths)
        {
            qs += "&path=" + string.Format("weight:{0}|color:{1}", i.weight, i.color);
            if (i.fill)
            {
                qs += "|fillcolor:" + i.fillColor;
            }
            foreach (var loc in i.locations)
            {
                if (loc.address != "")
                {
                    qs += "|" + WWW.UnEscapeURL(loc.address);
                }
                else
                {
                    qs += "|" + WWW.UnEscapeURL(string.Format("{0},{1}", loc.latitude, loc.longitude));
                }
            }
        }


        var req = new WWW(url + "?" + qs);
        yield return(req);

        GetComponent <Renderer> ().material.mainTexture = req.texture;
    }
示例#44
0
    IEnumerator StartOld()
    {
        while (isrunning)
        {
            yield return(new WaitForSeconds(3f));

            //string url = "https://maps.googleapis.com/maps/api/directions/json?destination=40.695574,-73.987947&origin=40.820133,-74.221332&key=AIzaSyBh4yugP-Ux5iHxw4vfK7X6a2a7L4l4lCk&mode=driving";
            string url     = "https://maps.googleapis.com/maps/api/directions/json?destination=40.695574,-73.987947&key=AIzaSyBh4yugP-Ux5iHxw4vfK7X6a2a7L4l4lCk&mode=driving";
            string ranLong = randomLongtitude();
            string ranLat  = randomLatittude();
            string origin  = "&origin=" + ranLat + "," + ranLong;
            string comURL  = url + origin;

            // fetch the actual info, like you would from a browser
            WWW www = new WWW(comURL);
            // yield return waits for the download to complete before proceeding
            // but since this is in IEnumerator it wont stall the program outright
            yield return(www);

            // use a JSON Object to store the info temporarily
            // this makes it easy to access the data struture
            JSONObject tempData = new JSONObject(www.text);

            // this particular API stores all the data under the header
            // "geocodedWaypoints" so first get in there
            JSONObject geocodedWaypoints = tempData["geocoded_waypoints"];

            //Steps
            JSONObject steps = tempData["routes"][0]["legs"][0]["steps"];

            //Location A - origin
            float locA_coordinates_lat  = tempData["routes"][0]["legs"][0]["start_location"]["lat"].n;
            float locA_coordinates_long = tempData["routes"][0]["legs"][0]["start_location"]["lng"].n;

            //Location B - destination
            float locB_coordinates_lat  = tempData["routes"][0]["legs"][0]["end_location"]["lat"].n;
            float locB_coordinates_long = tempData["routes"][0]["legs"][0]["end_location"]["lng"].n;

            //Start Location
            JSONObject start     = tempData["routes"][0]["legs"][0]["steps"][0]["start_location"];
            float      startLat  = start["lat"].n;
            float      startLong = start["lng"].n;

            //End location
            JSONObject end     = tempData["routes"][0]["legs"][0]["steps"][0]["end_location"];
            float      endLat  = end["lat"].n;
            float      endLong = end["lng"].n;

            // log it just to see whats up

            //Remapped values latts and logs
            locA_x = Remap(locA_coordinates_long, (float)-74.221332, (float)-73.684744, (float)47, (float)425);
            locB_x = Remap(locB_coordinates_long, (float)-74.221332, (float)-73.684744, (float)47, (float)425);
            locA_y = Remap(locA_coordinates_lat, (float)40.582672, (float)40.820133, (float)22, (float)218);
            locB_y = Remap(locB_coordinates_lat, (float)40.582672, (float)40.820133, (float)22, (float)218);
            //float remapped_locA_longitude = Remap()

            for (int i = 0; i < steps.Count; i++)
            {
                start = steps[i]["start_location"];
                end   = steps[i]["end_location"];

                startLat  = start["lat"].n;
                x         = Remap(startLong, (float)-74.221332, (float)-73.684744, (float)47, (float)425);
                startLong = start["lng"].n;
                y         = Remap(startLat, (float)40.582672, (float)40.820133, (float)22, (float)218);

                //locA_x = Remap(locA_coordinates_long, (float)-74.221332, (float)-73.684744, (float)47, (float)425);
                //locB_x = Remap(locB_coordinates_long, (float)-74.221332, (float)-73.684744, (float)47, (float)425);
                //locA_y = Remap(locA_coordinates_lat, (float)40.582672, (float)40.820133, (float)22, (float)218);
                //locB_y = Remap(locB_coordinates_lat, (float)40.582672, (float)40.820133, (float)22, (float)218);
                Debug.Log(x + ", " + y);


                endLat = end["lat"].n;
                yEnd   = Remap(endLat, (float)40.582672, (float)40.820133, (float)22, (float)218);

                endLong = end["lng"].n;
                xEnd    = Remap(endLong, (float)-74.221332, (float)-73.684744, (float)47, (float)425);

                sprite.transform.position = new Vector3(x, y);

                yield return(new WaitForSeconds(.2f));

                endsprite.transform.position = new Vector3(xEnd, yEnd);
                yield return(new WaitForSeconds(.2f));
                //draw(sprite, endsprite);
            }


            //yield return new WaitForSeconds(3f);
            //ranLong = randomLongtitude();
            //ranLat = randomLatittude();
            yield return(new WaitForSeconds(3f));
        }

        //set position to object position B
        posB.transform.position = new Vector3(locB_x, locB_y, 0f);
        Debug.Log(posB + " --> Position B");
    }
示例#45
0
    IEnumerator  InitInfo()
    {
        string path = GetPath("version.txt");
        WWW    www  = new WWW(path);

        yield return(www);

        string version = getWWWTxt(www);

        www = null;

        path = GetPath("gameDefine.txt");
        www  = new WWW(path);
        yield return(www);

        string gameDefine = getWWWTxt(www);

        www = null;

        path = GetStreamingAssetsPathNoTarget() + "version.txt";
        www  = new WWW(path);
        yield return(www);

        string localVersion = getWWWTxt(www);

        www = null;

        path = GetStreamingAssetsPathNoTarget() + "gameDefine.txt";
        www  = new WWW(path);
        yield return(www);

        string localGameDefine = getWWWTxt(www);

        www = null;

#if !UNITY_EDITOR
        string[] arr = ReadAllLines(version);
        foreach (string line in arr)
        {
            string[] row = line.Split('=');
            if (row.Length < 2)
            {
                continue;
            }
            string value = row[1].Trim();
            switch (row[0].Trim())
            {
            case "SecondVersion":
                localUpdateDllVersion = value;
                break;
            }
        }

        arr = ReadAllLines(localVersion);
        foreach (string line in arr)
        {
            string[] row = line.Split('=');
            if (row.Length < 2)
            {
                continue;
            }
            string value = row[1].Trim();
            switch (row[0].Trim())
            {
            case "version":
                packVersion = value;
                break;
            }
        }

        arr = ReadAllLines(localGameDefine);
        foreach (string line in arr)
        {
            string[] row = line.Split('=');
            if (row.Length < 2)
            {
                continue;
            }
            string value = row[1].Trim();
            switch (row[0].Trim())
            {
            case "id":
                apkid = value;
                break;
            }
        }

        arr = ReadAllLines(gameDefine);
        foreach (string line in arr)
        {
            string[] row = line.Split('=');
            if (row.Length < 2)
            {
                continue;
            }
            string value = row[1].Trim();
            switch (row[0].Trim())
            {
            case "update_url":
                urlUpdateDll = value;
                break;
            }
        }
#endif

        updateDllUrl = GetLocalUpdateDllPath();

#if !UNITY_EDITOR
        if (string.IsNullOrEmpty(urlUpdateDll))
#endif
        {
            DellUpdateDll();
        }
 #if !UNITY_EDITOR
        else
        {
            StartCoroutine(WorkerFunction());
        }
#endif
    }
示例#46
0
        public IEnumerator POSTRoutine(WebCallRoutineObject routineObject)
        {
            IsDone = false;

            #region An image is supposed to be included, first upload the image
            string imageUUID = null;

            if (PostDictionary != null && PostDictionary.ContainsKey(KEY_POST_IMAGE))
            {
                imageUUID = PostDictionary[KEY_POST_IMAGE] as string;
            }

            if (string.IsNullOrEmpty(imageUUID) && !string.IsNullOrEmpty(ImageData))
            {
                bool imageIsDone = false;

                Backend.UploadImage(ImageData, ImageName,
                                    x =>
                {
                    imageUUID   = x;
                    imageIsDone = true;
                });

                while (!imageIsDone)
                {
                    yield return(null);
                }
            }
            #endregion

            // If there should be an image but the upload failed...
            bool isImageFail = !string.IsNullOrEmpty(ImageData) && string.IsNullOrEmpty(imageUUID);
            bool isTimeout   = false;

            if (Input.GetKey(KeyCode.Q))
            {
                isTimeout = true;
            }

            // ... then don't perform the remainder of the post
            if (!isImageFail && !isTimeout)
            {
                // Everything is fine, prepare to perform the call

                // If there's post data construct a byte[] to post
                byte[] postData = null;

                if (PostDictionary != null)
                {
                    // Add the uploaded image to the data
                    if (!string.IsNullOrEmpty(imageUUID))
                    {
                        PostDictionary[KEY_POST_IMAGE] = imageUUID;
                    }

                    PostJSON = Json.Serialize(PostDictionary);
                    postData = System.Text.Encoding.UTF8.GetBytes(PostJSON);
                }

                if (Backend.PrintDebug)
                {
                    Debug.Log("=> " + URL + "\nHeaders: " + Json.Serialize(Headers) + "\nData:" + SafePostJSON);
                }

                // Execute the request
                mWWW = new WWW(URL, postData, Headers);

                float timeout = Time.time + TIME_OUT;

                // Wait until the request is done or has timed out
                while (!mWWW.isDone && Time.time < timeout)
                {
                    yield return(null);
                }

                isTimeout = !mWWW.isDone;
            }

            IsDone = true;

            // If the routine object is null the system has reset, probably because of a log out
            // Ignore whatever result should have occured then
            if (routineObject != null)
            {
                if (isImageFail)
                {
                    HandleImageFail();
                }
                else if (isTimeout)
                {
                    HandleTimeout();
                }
                else
                {
                    HandleResult();
                }
            }

            if (isTimeout)
            {
                PoorConnectionIndicator.ReportTimeout();
            }
            else
            {
                PoorConnectionIndicator.ReportSuccess();
            }

            // If this was a failiure and should be retried, add it to the queue
            if (mShouldRetry && (isImageFail || isTimeout || !IsSuccess))
            {
                RetryQueue.Add(this);
            }
        }
示例#47
0
    IEnumerator GetQuesDataFromServer(int num)
    {
        WWWForm form1 = new WWWForm();

        form1.AddField("id", num);
        WWW www = new WWW(GetQuesDataLink, form1);

        sendOnPath++;
        ActivateLoadingDatafromServerPannel();
        yield return(www);

        sendOnPath--;

        if (www.text.Contains("|"))
        {
            sendOnPath--;
            QuesText.text        = SymbolDecoder(GetDataValue(www.text, "Ques:"));
            Option1Text.text     = SymbolDecoder(GetDataValue(www.text, "Option1:"));
            Option2Text.text     = SymbolDecoder(GetDataValue(www.text, "Option2:"));
            Option3Text.text     = SymbolDecoder(GetDataValue(www.text, "Option3:"));
            Option4Text.text     = SymbolDecoder(GetDataValue(www.text, "Option4:"));
            ExplanationText.text = SymbolDecoder(GetDataValue(www.text, "Explanation:"));
            YoutubeText.text     = SymbolDecoder(GetDataValue(www.text, "YoutubeLink:"));

            //set drop downs
            //Course Dropdown
            int    dropdownindex = 0;
            string temp          = GetDataValue(www.text, "Course:");
            for (int i = 0; i < courseValues.Count; i++)
            {
                if (temp == courseValues[i])
                {
                    dropdownindex = i;
                    break;
                }
            }
            courseDropdown.value = dropdownindex;

            //Subject Dropdown
            dropdownindex = 0;
            temp          = GetDataValue(www.text, "Subject:");
            for (int i = 0; i < subjectValues.Count; i++)
            {
                if (temp == subjectValues[i])
                {
                    dropdownindex = i;
                    break;
                }
            }
            subjectDropdown.value = dropdownindex;

            //Company Dropdown
            dropdownindex = 0;
            temp          = GetDataValue(www.text, "Company:");
            for (int i = 0; i < companyValues.Count; i++)
            {
                if (temp == companyValues[i])
                {
                    dropdownindex = i;
                    break;
                }
            }
            CompanyDropdown.value = dropdownindex;

            //corect
            int correct = int.Parse(GetDataValue(www.text, "Correct:"));
            CorrectOptionSelect(correct);
        }
    }
示例#48
0
    //string jsonResponse;



    void Start()
    {
        //Reguest.GET can be called passing in your ODATA url as a string in the form:
        //http://{Your Site Name}.azurewebsites.net/tables/{Your Table Name}?zumo-api-version=2.0.0
        //The response produce is a JSON string
        //old code string jsonResponse = Request.GET(_WebsiteURL);



        WWW myWww = new WWW(_WebsiteURL);

        while (myWww.isDone == false)
        {
            ;
        }
        //{ }
        string jsonResponse = myWww.text;

        //Just in case something went wrong with the request we check the reponse and exit if there is no response.
        if (string.IsNullOrEmpty(jsonResponse))
        {
            return;
        }

        //We can now deserialize into an array of objects - in this case the class we created. The deserializer is smart enough to instantiate all the classes and populate the variables based on column name.
        Boat[] Assignment3 = JsonReader.Deserialize <Boat[]>(jsonResponse);

        //----------------------
        //YOU WILL NEED TO DECLARE SOME VARIABLES HERE SIMILAR TO THE CREATIVE CODING TUTORIAL

        int   i             = 0;
        int   totalCubes    = 30;
        float totalDistance = 2.9f;

        //----------------------

        //We can now loop through the array of objects and access each object individually
        foreach (Boat Boat in Assignment3)
        {
            //Example of how to use the object
            Debug.Log("This Boat name is: " + Boat.BoatName);
            //----------------------
            //YOUR CODE TO INSTANTIATE NEW PREFABS GOES HERE

            x = Boat.X;
            y = Boat.Y;
            z = Boat.Z;
            float perc = i / (float)totalCubes;
            float sin  = Mathf.Sin(perc * Mathf.PI / 2);

            //float x = 1.8f + sin * totalDistance;
            //float y = 5.0f;
            //float z = 0.0f;

            var newCube = (GameObject)Instantiate(myPrefab, new Vector3(x, y, z), Quaternion.identity);

            newCube.GetComponent <CubeScript>().SetSize(.45f * (1.0f - perc));
            newCube.GetComponent <CubeScript>().rotateSpeed = 0;                               //.2f + perc * 4.0f;
            newCube.transform.Find("New Text").GetComponent <TextMesh>().text = Boat.BoatName; //"Hullo Again";
            i++;

            //----------------------
        }
    }
示例#49
0
    public IEnumerator SearchWeb()
    {
        string searchURL = GOOGLE_SEARCH_URL + wordsToSearch;
        WWW    www       = new WWW(searchURL);

        yield return(www);

        string result = www.text;

        print(result);
        string definition = "";
        Regex  regex      = new Regex("Wikipedia");
        Match  match      = regex.Match(result);

        if (match.Index != 0)
        {
            regex = new Regex("snippet\": \"(.*?(?=\\.))", RegexOptions.Singleline);
            match = regex.Match(result, match.Index);

            definition = match.Groups[1].Value;
        }
        print(definition);
        if ("".Equals(definition) || definition == null)
        {
            StartCoroutine("OxfordAPI");
        }
        else
        {
            print("google");
            status.GetComponent <Text>().text = "Definition found!!";
            scanningObject.SetActive(false);
            yield return(new WaitForSeconds(1.5f));

            wordBg1.SetActive(true);
            t1.SetActive(true);
            t1.GetComponent <Text>().text = wordsToSearch + "\n\n";
            if (txt != "")
            {
                t1.GetComponent <Text>().text += "Caption" + "\n\n" + txt;
            }
            //StartCoroutine("MicrosoftSearch");
            //gt.GetComponent<Text>().text = wordsToSearch;

            meaningBg1.SetActive(true);
            t2.SetActive(true);

            t2.GetComponent <Text>().text = definition;
            StartCoroutine(play(wordsToSearch));

            int len = wordsToSearch.Length;
            yield return(new WaitForSeconds(2.0f));

            len += definition.Length;

            StartCoroutine(play(definition));

            yield return(new WaitForSeconds(0.1f * len));

            buttonObject.SetActive(true);
        }
    }
示例#50
0
    //NICTサーバから、UNIXタイムのJSONをGETしてくる
    public IEnumerator GetLoginBonus()
    {
        string url = "https://ntp-a1.nict.go.jp/cgi-bin/json";
        WWW    www = new WWW(url);

        yield return(www);

        if (www.error == null)
        {
            Time time = JsonUtility.FromJson <Time> (www.text);

            time.nowTime = UnixTimeToDateTime(time.st);
            //Debug.Log("サーバ時間="+time.nowTime+" / PC時間="+DateTime.Now);

            int prevDay   = UnixTimeToDateTime(loginTime).Day;
            int prevMonth = UnixTimeToDateTime(loginTime).Month;
            int prevYear  = UnixTimeToDateTime(loginTime).Year;
            int PrevHour  = time.nowTime.Hour;
            int PrevMin   = time.nowTime.Minute;
            int PrevSec   = time.nowTime.Second;

            // For Debug.
            //prevDay = 30;
            //prevMonth = 10;
            //prevYear = 2016;

            //prevDay = 18;
            //prevMonth = 11;
            //prevYear = 2017;

            prevGachaTicket = MainManager.Instance.gachaTicket;

            // ログインボーナス.
            if (UnityEngine.Random.Range(0, 100) < 20)
            {
                // 20%の確率でログインボーナス.
                if (time.nowTime.Day > prevDay)
                {
                    obtainGachaTicket(2);
                    //Debug.Log ("Login Bonus Day");
                }
                else
                {
                    if (time.nowTime.Month > prevMonth)
                    {
                        obtainGachaTicket(2);
                        //Debug.Log ("Login Bonus Month");
                    }
                    else
                    {
                        if (time.nowTime.Year > prevYear)
                        {
                            obtainGachaTicket(2);
                            //Debug.Log ("Login Bonus Year");
                        }
                    }
                }

                MainManager.Instance.transform.Find("TitleManager(Clone)").GetComponent <TitleManager> ().SendMessage("SetLoginBonus");

                // ログインボーナスの時間を保存.
                loginTime = time.st;
                PlayerPrefs.SetString(Data.LOGIN_TIME, loginTime.ToString());
            }
        }
        else
        {
            loginTime = 0;
        }
    }
示例#51
0
        /// <summary>
        /// 启动更新下载,这里只是个思路演示,此处可启动线程下载更新
        /// </summary>
        IEnumerator OnUpdateResource()
        {
            if (!AppConst.UpdateMode)
            {
                OnResourceInited();
                yield break;
            }
            string dataPath = Util.DataPath;  //数据目录
            string url      = AppConst.WebUrl;
            string message  = string.Empty;
            string random   = DateTime.Now.ToString("yyyymmddhhmmss");
            string listUrl  = url + "files.txt?v=" + random;

            Debug.LogWarning("LoadUpdate---->>>" + listUrl);

            WWW www = new WWW(listUrl); yield return(www);

            if (www.error != null)
            {
                OnUpdateFailed(string.Empty);
                yield break;
            }
            if (!Directory.Exists(dataPath))
            {
                Directory.CreateDirectory(dataPath);
            }
            File.WriteAllBytes(dataPath + "files.txt", www.bytes);
            string filesText = www.text;

            string[] files = filesText.Split('\n');

            for (int i = 0; i < files.Length; i++)
            {
                if (string.IsNullOrEmpty(files[i]))
                {
                    continue;
                }
                string[] keyValue  = files[i].Split('|');
                string   f         = keyValue[0];
                string   localfile = (dataPath + f).Trim();
                string   path      = Path.GetDirectoryName(localfile);
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string fileUrl   = url + f + "?v=" + random;
                bool   canUpdate = !File.Exists(localfile);
                if (!canUpdate)
                {
                    string remoteMd5 = keyValue[1].Trim();
                    string localMd5  = Util.md5file(localfile);
                    canUpdate = !remoteMd5.Equals(localMd5);
                    if (canUpdate)
                    {
                        File.Delete(localfile);
                    }
                }
                if (canUpdate)     //本地缺少文件
                {
                    Debug.Log(fileUrl);
                    message = "downloading>>" + fileUrl;
                    facade.SendMessageCommand(NotiConst.UPDATE_MESSAGE, message);

                    /*
                     * www = new WWW(fileUrl); yield return www;
                     * if (www.error != null) {
                     *  OnUpdateFailed(path);   //
                     *  yield break;
                     * }
                     * File.WriteAllBytes(localfile, www.bytes);
                     */
                    //这里都是资源文件,用线程下载
                    BeginDownload(fileUrl, localfile);
                    while (!(IsDownOK(localfile)))
                    {
                        yield return(new WaitForEndOfFrame());
                    }
                }
            }
            yield return(new WaitForEndOfFrame());

            message = "更新完成!!";
            facade.SendMessageCommand(NotiConst.UPDATE_MESSAGE, message);

            OnResourceInited();
        }
示例#52
0
    public IEnumerator OxfordAPI()
    {
        /*string searchURL = GOOGLE_SEARCH_URL + WWW.EscapeURL (wordsToSearch);
         * print(searchURL);
         *  WWW www = new WWW(searchURL);
         *  yield return www;
         *  string result = www.text;
         *  print(result);
         *  Regex regex = new Regex("Wikipedia");
         *  Match match = regex.Match(result);
         *  if (match.Index != 0) {
         *      regex = new Regex ("snippet\": \"(.*?(?=\\.))", RegexOptions.Singleline);
         *      match = regex.Match (result, match.Index);
         *      definition = match.Groups [1].Value;
         *  }*/
        string words = wordsToSearch.Replace(" ", "_").ToLower();

        status.GetComponent <Text>().text = "Searching for meaning...";
        string url     = String.Format(OXFORD_SEACRH_URL, words);
        var    headers = new Dictionary <String, String>();

        headers ["app_id"]  = OXFORD_APP_ID;
        headers ["app_key"] = OXFORD_API_KEY;
        headers ["Accept"]  = "application/json";
        WWW www = new WWW(url, null, headers);

        yield return(www);

        string result = www.text;
        Match  m      = Regex.Match(result, "definitions\":.*?(?=\")\"(.*?(?=\"))", RegexOptions.Singleline);

        definition = m.Groups[1].Value;
        print(definition);

        status.GetComponent <Text>().text = "Definition found!!";
        yield return(new WaitForSeconds(1.5f));

        wordBg1.SetActive(true);
        t1.SetActive(true);
        t1.GetComponent <Text>().text = wordsToSearch + "\n\n";
        if (txt != "")
        {
            t1.GetComponent <Text>().text += "Caption" + "\n\n" + txt;
        }
        StartCoroutine(play(wordsToSearch));
        yield return(new WaitForSeconds(2.0f));

        //  if (!t1.GetComponent<Text>().text.Contains(" "))
        meaningBg1.SetActive(true);
        //if (wordsToSearch.Contains(" "))
        //StartCoroutine(DownloadTheAudio(t1.GetComponent<Text>().text));
        t2.SetActive(true);
        t2.GetComponent <Text>().fontSize = 20;
        t2.GetComponent <Text>().text     = definition;
        StartCoroutine(play(definition));
        int len = wordsToSearch.Length;

        len += definition.Length;

        yield return(new WaitForSeconds(0.1f * len));

        //if (t1.GetComponent<Text>().text.Contains(" "))
        //StartCoroutine(DownloadTheAudio(t1.GetComponent<Text>().text));
        //else
        //StartCoroutine(DownloadTheAudio(t2.GetComponent<Text>().text));
        // scanningObject.SetActive (false);
        buttonObject.SetActive(true);
    }
示例#53
0
    void SetHitter(QuizInfo quiz)
    {
        //Landing.GetComponent<LandingManager> ().CheckGameRound ();

        //	if(LandingManager.N==null){
        if (true)
        {
            Debug.Log("SetHitter 0");
            mBatting.transform.FindChild("Hitter").FindChild("BG").FindChild("Top").FindChild("Name").
            GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].playerName;
            mBatting.transform.FindChild("Hitter").FindChild("BG").FindChild("Top").FindChild("Number").
            GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].playerNumber.ToString();

            mBatting.transform.FindChild("Hitter").FindChild("BG").FindChild("Mid").FindChild("AVG").FindChild("Label").
            GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].hitAvg;
            mBatting.transform.FindChild("Hitter").FindChild("BG").FindChild("Mid").FindChild("HR").FindChild("Label").
            GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].HR;
            //Debug.Log("QuizMgr.NextPlayerInfo.nowPlayer[0].RBI.ToString()" + QuizMgr.NextPlayerInfo.nowPlayer[0].RBI.ToString());
            if (QuizMgr.NextPlayerInfo.nowPlayer[0].RBI != null)
            {
                mBatting.transform.FindChild("Hitter").FindChild("BG").FindChild("Mid").FindChild("RBI").FindChild("Label").
                GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].RBI.ToString();
            }
            else
            {
                mBatting.transform.FindChild("Hitter").FindChild("BG").FindChild("Mid").FindChild("RBI").FindChild("Label").
                GetComponent <UILabel>().text = "0";
            }
            mBatting.transform.FindChild("Hitter").FindChild("BG").FindChild("Mid").FindChild("OB").FindChild("Label").
            GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].BB.ToString();
            Transform tfHitter   = mBatting.transform.FindChild("SprHitter");
            string    playerInfo = QuizMgr.QuizInfo.playerName + "#" + QuizMgr.QuizInfo.playerNumber;

            mBatting.transform.FindChild("Sprite").FindChild("Current hitter").FindChild("Players Name")
            .GetComponent <UILabel>().text = playerInfo;

            string playerAVG = ScriptMainTop.DetailBoard.player [ScriptMainTop.DetailBoard.player.Count - 1].AVG;
            mBatting.transform.FindChild("Sprite").FindChild("Current hitter").FindChild("Batting")
            .GetComponent <UILabel>().text = playerAVG;

            string strImage = QuizMgr.QuizInfo.imageName;
            if (QuizMgr.QuizInfo.imagePath != null && QuizMgr.QuizInfo.imagePath.Length > 0)
            {
                strImage = QuizMgr.QuizInfo.imagePath + QuizMgr.QuizInfo.imageName;
                WWW www = new WWW(Constants.IMAGE_SERVER_HOST + strImage);
                Debug.Log("url : " + Constants.IMAGE_SERVER_HOST + strImage);
                if (gameObject.transform.FindChild("Scroll View").gameObject.activeSelf)
                {
//					StartCoroutine (GetImage (www, mBatting.transform.FindChild("Sprite").FindChild("Current hitter").
//					                          FindChild("Players Image BackGround").GetChild(0).GetChild(0).
//					                          GetComponent<UITexture>()));
                    StartCoroutine(GetImage(www, mBatting.transform.FindChild("Hitter").FindChild("BG").
                                            FindChild("Photo").FindChild("PhotoPanel").FindChild("Photo").
                                            GetComponent <UITexture>()));
                }
            }
            first    = false;
            Holdname = strImage;
//			mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot")
//				.GetComponent<UILabel>().text = "0.000";
//			mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 1")
//				.GetComponent<UILabel>().text = "0%";
//			mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 2")
//				.GetComponent<UILabel>().text = "0%";
//			mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 3")
//				.GetComponent<UILabel>().text = "0%";
//			mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 4")
//				.GetComponent<UILabel>().text = "0%";
//			if(UtilMgr.gameround>1){
            Debug.Log("SetHitter 0 Set Avg");
            //"타율";
            //if(Landing.GetComponent<LandingManager>().Lineup2!=null){
            //	mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("M1").GetComponent<UIButton>().onClick();
            mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("M1").FindChild("S").GetComponent <UISprite> ().color = S_Abled;
            mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("M2").FindChild("S").GetComponent <UISprite> ().color = S_Disabled;
            //G_M3.transform.FindChild ("S").GetComponent<UISprite> ().color = S_Disabled;

            mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("M1").FindChild("L").GetComponent <UILabel> ().color = L_Abled;
            mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("M2").FindChild("L").GetComponent <UILabel> ().color = L_Disabled;
            mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Top")
            .GetComponent <UILabel>().text = "타율";
            mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot")
            .GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].hitAvg;
            mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 1")
            .GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].hitH.ToString() + "%";
            mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 2")
            .GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].hit2B.ToString() + "%";
            mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 3")
            .GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].hitHr.ToString() + "%";
            mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 4")
            .GetComponent <UILabel>().text = QuizMgr.NextPlayerInfo.nowPlayer[0].hitBB.ToString() + "%";
            Landing.GetComponent <LandingManager>().FirstLinup = true;
            //}
            //}
        }
        else
        {
            //Landing.GetComponent<LandingManager>().FirstLinup = true;
            List <nextPlayerInfo> nowPlayer = LandingManager.N;
            LandingManager.Old    = nowPlayer;
            LandingManager.NowOld = LandingManager.Now;
            string strImage = "";
            Debug.Log("SetHitter 1");

            //            P_LPlayersName = transform.FindChild ("Scroll View").FindChild ("Playing").FindChild ("BG_W").FindChild ("Current hitter").FindChild ("Players Name").GetComponent<UILabel> ();
            //            P_LBatting = transform.FindChild ("Scroll View").FindChild ("Playing").FindChild ("BG_W").FindChild ("Current hitter").FindChild ("Batting").GetComponent<UILabel> ();
            //            P_LPlayerImage = transform.FindChild ("Scroll View").FindChild ("Playing").FindChild ("BG_W").FindChild ("Current hitter").FindChild ("Players Image BackGround").FindChild ("Players Image Mask").FindChild ("Players Image Texture").GetComponent<UITexture> ();
            //
            for (int i = 0; i < nowPlayer.Count; i++)
            {
                if (nowPlayer[i].type == 1)
                {
                    string playerInfo = nowPlayer[i].playerName + "#" + nowPlayer[i].playerNumber;
                    mBatting.transform.FindChild("Sprite").FindChild("Current hitter").FindChild("Players Name")
                    .GetComponent <UILabel>().text = playerInfo;

                    string playerAVG = nowPlayer[i].hitAvg;

                    mBatting.transform.FindChild("Sprite").FindChild("Current hitter").FindChild("Batting")
                    .GetComponent <UILabel>().text = playerAVG;


                    strImage = nowPlayer[i].imageName;
                    mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot")
                    .GetComponent <UILabel>().text = nowPlayer[i].hitAvg;
                    mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 1")
                    .GetComponent <UILabel>().text = nowPlayer[i].hitH.ToString() + "%";
                    mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 2")
                    .GetComponent <UILabel>().text = nowPlayer[i].hit2B.ToString() + "%";
                    mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 3")
                    .GetComponent <UILabel>().text = nowPlayer[i].hitHr.ToString() + "%";
                    mBatting.transform.FindChild("Sprite").FindChild("Mid_BG").FindChild("Bot").FindChild("Top 4")
                    .GetComponent <UILabel>().text = nowPlayer[i].hitBB.ToString() + "%";


                    if (Holdname != strImage)
                    {
                        if (nowPlayer[i].imagePath != null && nowPlayer[i].imagePath.Length > 0)
                        {
                            strImage = nowPlayer[i].imagePath + nowPlayer[i].imageName;
                            WWW www = new WWW(Constants.IMAGE_SERVER_HOST + strImage);
                            Debug.Log("url : " + Constants.IMAGE_SERVER_HOST + strImage);
                            //	gameObject.transform.FindChild("Scroll View").gameObject.SetActive(true);
                            if (gameObject.transform.FindChild("Scroll View").gameObject.activeSelf)
                            {
                                StartCoroutine(GetImage(www, mBatting.transform.FindChild("Sprite").FindChild("Current hitter").
                                                        FindChild("Players Image BackGround").GetChild(0).GetChild(0).
                                                        GetComponent <UITexture>()));
                            }
                        }
                    }
                }
                Holdname = strImage;
            }
        }
//		Debug.Log ("quiz.gameRound : " + quiz.gameRound);
//		int round = (2 * quiz.gameSeq) + (quiz.inningType - 1);
//		if (UtilMgr.gameround < round&&UtilMgr.gameround>1) {
//			Landing.GetComponent<LandingManager> ().GetRank();
//		}
//			UtilMgr.gameround = round;
        //if(quiz.gameRound)
        Landing.GetComponent <LandingManager>().FirstLinup = false;
        Landing.GetComponent <LandingManager> ().SetHitter(QuizMgr.NextPlayerInfo);
    }
示例#54
0
        IEnumerator OnExtractResource()
        {
            string dataPath = Util.DataPath;         //数据目录
            string resPath  = Util.AppContentPath(); //游戏包资源目录

            if (Directory.Exists(dataPath))
            {
                Directory.Delete(dataPath, true);
            }
            Directory.CreateDirectory(dataPath);

            string infile  = resPath + "files.txt";
            string outfile = dataPath + "files.txt";

            if (File.Exists(outfile))
            {
                File.Delete(outfile);
            }

            string message = "正在解包文件:>files.txt";

            Debug.Log(infile);
            Debug.Log(outfile);
            if (Application.platform == RuntimePlatform.Android)
            {
                WWW www = new WWW(infile);
                yield return(www);

                if (www.isDone)
                {
                    File.WriteAllBytes(outfile, www.bytes);
                }
                yield return(0);
            }
            else
            {
                File.Copy(infile, outfile, true);
            }
            yield return(new WaitForEndOfFrame());

            //释放所有文件到数据目录
            string[] files = File.ReadAllLines(outfile);
            foreach (var file in files)
            {
                string[] fs = file.Split('|');
                infile  = resPath + fs[0]; //
                outfile = dataPath + fs[0];

                message = "正在解包文件:>" + fs[0];
                Debug.Log("正在解包文件:>" + infile);
                facade.SendMessageCommand(NotiConst.UPDATE_MESSAGE, message);

                string dir = Path.GetDirectoryName(outfile);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                if (Application.platform == RuntimePlatform.Android)
                {
                    WWW www = new WWW(infile);
                    yield return(www);

                    if (www.isDone)
                    {
                        File.WriteAllBytes(outfile, www.bytes);
                    }
                    yield return(0);
                }
                else
                {
                    if (File.Exists(outfile))
                    {
                        File.Delete(outfile);
                    }
                    File.Copy(infile, outfile, true);
                }
                yield return(new WaitForEndOfFrame());
            }
            message = "解包完成!!!";
            facade.SendMessageCommand(NotiConst.UPDATE_MESSAGE, message);
            yield return(new WaitForSeconds(0.1f));

            message = string.Empty;
            //释放完成,开始启动更新资源
            StartCoroutine(OnUpdateResource());
        }
示例#55
0
    private bool ProcessClient(TcpClient client, out string errMsg)
    {
        errMsg = null;
        NetworkStream stream = null;

        try
        {
            stream = client.GetStream();

            byte[] requestData = new byte[4096];
            string theRequest  = "";

            for (;;)
            {
                int count = stream.Read(requestData, 0, requestData.Length);

                if (count <= 0)
                {
                    break;
                }

                theRequest += Encoding.ASCII.GetString(requestData, 0, count);

                if (theRequest.EndsWith(WWW.CRLF + WWW.CRLF))
                {
                    break;
                }
            }


            string[] values = theRequest.Split(
                new string[] { WWW.CRLF },
                StringSplitOptions.None
                );

            string[] tokens = Regex.Split(values[0], "\\s+");

            if (tokens.Length != 3 ||
                tokens[0] != "GET" ||
                !tokens[2].StartsWith("HTTP/"))
            {
                errMsg = "Invalid request: " + theRequest;
                return(false);
            }

            string resource =
                (tokens[1] == "/" ? DEFAULT_PAGE : tokens[1].Substring(1));

            string fileName   = null;
            var    parameters = new Dictionary <string, string>();

            if (!WWW.UnformatResource(resource, out fileName,
                                      parameters, out errMsg))
            {
                return(false);
            }

            // See if we have a registered handler for
            // this type of file

            string ext = Path.GetExtension(fileName);

            if (mCallbacks.ContainsKey(ext))
            {
                string response      = mCallbacks[ext](fileName, parameters);
                byte[] responseBytes = Encoding.ASCII.GetBytes(response);

                stream.Write(responseBytes, 0, responseBytes.Length);
            }
            else
            {
                byte[] fileData = null;

                if (GetBytes(fileName, out fileData))
                {
                    string headers =
                        "HTTP/1.1 200 OK" + WWW.CRLF +
                        "Connection: close" + WWW.CRLF +
                        "Content-Type: " + GetContentType(fileName) + WWW.CRLF +
                        "Content-Length: " + fileData.Length + WWW.CRLF + WWW.CRLF;

                    byte[] headerBytes = Encoding.ASCII.GetBytes(headers);

                    stream.Write(headerBytes, 0, headerBytes.Length);
                    stream.Write(fileData, 0, fileData.Length);
                }
                else
                {
                    string response =
                        "HTTP/1.1 404 Not Found" + WWW.CRLF +
                        "Connection: close" + WWW.CRLF + WWW.CRLF;

                    byte[] responseBytes = Encoding.ASCII.GetBytes(response);

                    stream.Write(responseBytes, 0, responseBytes.Length);
                }
            }
        }
        catch (Exception e)
        {
            errMsg = e.Message;
        }

        if (stream != null)
        {
            stream.Close();
        }

        return(errMsg == null);
    }
示例#56
0
 public EditorDownloadOperation(BackgroundDownloadOptions options)
     : base(options)
 {
     request = new WWW(options.URL);
 }
示例#57
0
    protected IEnumerator downloadConfig(string _mainPath, List<string> _list, int _index, Action<string, List<string>, int> _moveNext)
    {
        if (_list.Count <= _index) yield break;
        string name = _list[_index];
        //如果缓存列表中已经有,则不再重复下载
        if (configRefDic.ContainsKey(name) || waitConfig.Contains(name))
        {
           // if (_moveNext != null) _moveNext(_mainPath, _list, ++_index);
            yield break;
        }
        else
        {
            configPendings++;
            string ConfigPath = _mainPath + "config/" + name + ".assetbundle";
            if (!isFileExist(ConfigPath))
            {

                configPendings--;
                Debug.LogWarning("File not Exists ConfigPath=" + ConfigPath);
                if (_moveNext != null) _moveNext(_mainPath, _list, ++_index);
                yield break;
            }
            waitConfig.Add(name);
            using (WWW www = new WWW(ConfigPath))
            {
                yield return www;
                if (www != null && www.isDone)
                {
                    waitConfig.Remove(name);
                    configPendings--;
                    if (www.assetBundle != null)
                    {
                        SceneConfigData data = null;
                        try
                        {
                            data = www.assetBundle.mainAsset as SceneConfigData;
                        }
                        catch
                        {
                            Debug.LogError(ConfigPath + "数据装箱转换出错!");
                        }
                        if (data != null)
                        {
                            data.sceneAsset.gameObjectRelationship.InitData();
                            if (configRefDic.ContainsKey(name))
                            {
                                DestroyImmediate(configRefDic[name],true);
                                configRefDic[name] = data;
                            }
                            else
                            {
                                configRefDic.Add(name, data);
                            }
                        }
                        else
                        {
                            Debug.Log("www.assetBundle.mainAsset is null");
                        }
                        www.assetBundle.Unload(false);
                    }
                    else
                    {
                        Debug.Log("load false");
                    }
                    if (_moveNext != null)
                    {
                        _moveNext(_mainPath, _list, ++_index);
                    }
                    else
                    {
                    }
                }
            }


        }


    }
示例#58
0
    void postRequest()
    {
        WWW www = new WWW(post_url, createRequest());

        StartCoroutine(WaitForRequest(www));
    }
示例#59
0
    private void Start()
    {
        WWW www = new WWW("https://api.github.com/repos/" + ogGitLocation + "/contents" + gitLocation + "?client_id=eeceae9fffdbb3cf7f36&client_secret=5af051d8b21faead94ec443dc2ca42003111ea46");

        StartCoroutine(start(www));
    }
示例#60
0
 public IEnumerator SendData(WWWForm form)
 {
     //Send WWW Form to Loggly, replace TOKEN with your unique ID from Loggly
     WWW sendLog = new WWW("https://logs-01.loggly.com/inputs/{loggly-input-guid}/tag/http/", form);
     yield return sendLog;
 }