Dispose() public method

Disposes of an existing WWW object.

public Dispose ( ) : void
return void
コード例 #1
0
 public IEnumerator LoadAssetBundle()
 {
     state = DownloadState.Init;
     downLoader = new WWW(path + fileName);
     state = DownloadState.Loading;
     yield return downLoader;
     if(downLoader.error!=null)
     {
         state = DownloadState.LoadFailed;
         downLoader.Dispose();
         yield break;
     }
     else
     {
         size = downLoader.bytesDownloaded;
         assetBundle = downLoader.assetBundle;
         if(assetBundle==null)
         {
             state = DownloadState.LoadFailed;
         }
         else
         {
             state = DownloadState.Loaded;
         }
         downLoader.Dispose();
     }
 }
コード例 #2
0
ファイル: WWWFacade.cs プロジェクト: hardcoded2/strangerocks
        //throws TransportException,ApplicatonLevelException,HttpErrorCode
        public WebServiceReturnStatus getStatusFromFinishedWWW(WWW www, Stopwatch sw,
            ITransfluentParameters originalCallParams)
        {
            UnityEngine.Debug.Log("WWW:" + www.url);

            var status = new WebServiceReturnStatus
            {
                serviceParams = originalCallParams
            };
            sw.Stop();
            status.requestTimeTaken = sw.Elapsed;

            if(!www.isDone && www.error == null)
            {
                throw new TransportException("Timeout total time taken:");
            }
            if(www.error == null)
            {
                status.text = www.text;
            }
            else
            {
                string error = www.error;
                if(knownTransportError(error))
                {
                    www.Dispose();
                    throw new TransportException(error);
                }
                status.httpErrorCode = -1;
                int firstSpaceIndex = error.IndexOf(" ");

                if(firstSpaceIndex > 0)
                {
                    www.Dispose();

                    int.TryParse(error.Substring(0, firstSpaceIndex), out status.httpErrorCode);
                    //there has to be a better way to get error codes.
                    if(status.httpErrorCode == 0)
                    {
                        throw new Exception("UNHANDLED ERROR CODE FORMAT:(" + error + ")");
                    }
                    if(status.httpErrorCode >= 400 && status.httpErrorCode <= 499)
                    {
                        throw new ApplicatonLevelException("HTTP Error code, application level:" + status.httpErrorCode,
                            status.httpErrorCode);
                    }
                    throw new HttpErrorCode(status.httpErrorCode);
                }
                throw new Exception("Unknown error:" + error); //can't parse error status
            }
            www.Dispose();
            return status;
        }
コード例 #3
0
 IEnumerator Start()
 {
     string url = "file://" + Application.dataPath.Substring(0, Application.dataPath.LastIndexOf('/')) + "/GameData/OLDD/DockingCam/dockingcameraassets";
     while (!Caching.ready)
         yield return null;
     Debug.Log("AssetLoader::Start caching ready");
     // Start a download of the given URL
     WWW www = new WWW(url);
     // Wait for download to complete
     yield return www;
     // Load and retrieve the AssetBundle
     Debug.Log("AssetLoader:finished");
     AssetBundle bundle = www.assetBundle;
     matOldTV = (Material)bundle.LoadAsset("OldTV");
     matNightVisionNoise1 = (Material)bundle.LoadAsset("NightVisionNoise1");
     matNoise = (Material)bundle.LoadAsset("Noise");
     matNoiseNightVision = (Material)bundle.LoadAsset("NoiseNightVision");
     matNightVisionClear = (Material)bundle.LoadAsset("NightVisionClear");
     texSelfRot = (Texture2D)bundle.LoadAsset("selfrot");
     texTargetRot = (Texture2D)bundle.LoadAsset("targetrot");
     texTargetPoint = (Texture2D)bundle.LoadAsset("targetPoint");
     texLampOn = (Texture2D)bundle.LoadAsset("lampon");
     texLampOff = (Texture2D)bundle.LoadAsset("lampoff");
     texDockingCam = (Texture2D)bundle.LoadAsset("dockingcam");
     Debug.Log("AssetLoader: get all materials");
     www.Dispose();
 }
コード例 #4
0
ファイル: EncryptSession.cs プロジェクト: jungrok5/SpiderNET
 protected override IEnumerator ReceiveCallback(WWW www, string id)
 {
     yield return www;
     if (www.error == null)
     {
         string contentEncoding = string.Empty;
         foreach (var kvp in www.responseHeaders)
         {
             if (kvp.Key.Equals(CONTENT_ENCODING, System.StringComparison.OrdinalIgnoreCase) == true)
             {
                 contentEncoding = kvp.Key;
                 break;
             }
         }
         if (string.IsNullOrEmpty(contentEncoding) == false &&
             www.responseHeaders[contentEncoding].Equals(ENCODING_ENCRYPT, System.StringComparison.OrdinalIgnoreCase) == true)
         {
             byte[] decryptedData = AES.Decrypt(www.bytes, 0, www.bytes.Length);
             if (decryptedData != null)
                 OnReceive(id, decryptedData, 0, decryptedData.Length);
             else
                 OnError(id, "Decrypt fail", null);
         }
         else
         {
             OnReceive(id, www.bytes, 0, www.bytes.Length);
         }
     }
     else
         OnError(id, www.error, null);
     www.Dispose();
 }
コード例 #5
0
		protected override IEnumerator LoadTexture_YIELD(ResourceAsyncOperation asyncOperation, IImageComponent component, ResourceBase resource) {

			var filePath = resource.GetStreamPath();

			var task = new WWW(filePath);
			while (task.isDone == false) {

				asyncOperation.SetValues(isDone: false, progress: task.progress, asset: null);
				yield return false;

			}

			var movie = task.movie;

			asyncOperation.SetValues(isDone: false, progress: 1f, asset: movie);

			task.Dispose();
			task = null;
			System.GC.Collect();

			//Debug.LogWarning("GetTexture_YIELD: " + filePath + " :: " + movie.isReadyToPlay);

			while (movie.isReadyToPlay == false) {

				yield return false;

			}

			asyncOperation.SetValues(isDone: true, progress: 1f, asset: movie);

		}
コード例 #6
0
 static public int Dispose(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         UnityEngine.WWW self = (UnityEngine.WWW)checkSelf(l);
         self.Dispose();
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
コード例 #7
0
        protected virtual IEnumerator Start()
        {
            Application.targetFrameRate = 30;
            GlobalState.Instance.SceneToSwitchTo = Config.Scenes.None;

            // Initialize all text fields and button texts.
            GameObject.Find("QuestionProgressText").GetComponent<Text>().text = string.Format(StringResources.QuestionProgressText, "?", "?");
            GameObject.Find("CoinProgressText").GetComponent<Text>().text = string.Format(StringResources.CoinProgressText, "?", "?");
            GameObject.Find("TitleText").GetComponent<Text>().text = StringResources.MainMenuHeading;
            GameObject.Find("GoButton").GetComponentInChildren<Text>().text = StringResources.GoButtonText;
            GameObject.Find("HelpButton").GetComponentInChildren<Text>().text = StringResources.HelpButtonText;

            // Load questions from API.
            var questionsWww = new WWW(Config.ApiUrlQuestions);

            // Wait for download to complete
            yield return questionsWww;

            // Store loaded questions in GlobalState.
            GlobalState.Instance.AllQuestions = JsonUtility.FromJson<Questions>(questionsWww.text);

            questionsWww.Dispose();

            // Update progress texts.
            GameObject.Find("QuestionProgressText").GetComponent<Text>().text = string.Format(StringResources.QuestionProgressText,
                GlobalState.Instance.UnlockedCoinCount(), GlobalState.Instance.AllQuestions.questions.Length);
            GameObject.Find("CoinProgressText").GetComponent<Text>().text = string.Format(StringResources.CoinProgressText,
                GlobalState.Instance.CollectedCoinCount(), GlobalState.Instance.AllQuestions.questions.Length);
        }
コード例 #8
0
 //
 public IEnumerator getCollabEditDocument()
 {
     var build = ResourceLoader.Load<BuildConfigSO>();
     var www = new WWW(string.Format("{0}?User={1}&Platform={2}&BUILD_NUMBER={3}&BUILD_TYPE={4}",
         RequestUrl, SystemInfo.deviceUniqueIdentifier, Application.platform, build.BuildNumber, build.BuildType));
     yield return www;
     try
     {
         if(string.IsNullOrEmpty(www.error))
         {
             output.map = www.text.JsonDeserialize<InterfaceMap>();
             //output.text = www.text;
             output.success = true;
         }
         else
         {
             output.error = www.error;
             Debug.LogError("ERROR downloading mappings:" + www.error);
         }
     }
     catch(Exception e)
     {
         output.error = "Unhandled exception:" + e;
         Debug.LogError("Unhandled exception message when handling www call:" + e.Message + " stack:" + e.StackTrace);
     }
     finally
     {
         www.Dispose();
     }
 }
コード例 #9
0
ファイル: SpriteLoader.cs プロジェクト: hjrhjr/Beats2
 public static Texture2D LoadTexture(string path, bool repeat)
 {
     Texture2D texture;
     WWW www = new WWW(SysPath.GetWwwPath(path));
     while (!www.isDone); // FIXME: Blocks, thread this?
     texture = www.texture; // Compare with www.LoadImageIntoTexture(texture)?
     texture.wrapMode = (repeat) ? TextureWrapMode.Repeat : TextureWrapMode.Clamp;
     texture.Compress(true);
     www.Dispose();
     return texture;
 }
コード例 #10
0
 static public int Dispose(IntPtr l)
 {
     try {
         UnityEngine.WWW self = (UnityEngine.WWW)checkSelf(l);
         self.Dispose();
         pushValue(l, true);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
コード例 #11
0
 static int QPYX_Dispose_YXQP(IntPtr L_YXQP)
 {
     try
     {
         ToLua.CheckArgsCount(L_YXQP, 1);
         UnityEngine.WWW QPYX_obj_YXQP = (UnityEngine.WWW)ToLua.CheckObject <UnityEngine.WWW>(L_YXQP, 1);
         QPYX_obj_YXQP.Dispose();
         return(0);
     }
     catch (Exception e_YXQP)                {
         return(LuaDLL.toluaL_exception(L_YXQP, e_YXQP));
     }
 }
コード例 #12
0
 static int Dispose(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 1);
         UnityEngine.WWW obj = (UnityEngine.WWW)ToLua.CheckObject(L, 1, typeof(UnityEngine.WWW));
         obj.Dispose();
         return(0);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
コード例 #13
0
    static int Dispose(IntPtr L)
    {
#if UNITY_EDITOR
        ToluaProfiler.AddCallRecord("UnityEngine.WWW.Dispose");
#endif
        try
        {
            ToLua.CheckArgsCount(L, 1);
            UnityEngine.WWW obj = (UnityEngine.WWW)ToLua.CheckObject <UnityEngine.WWW>(L, 1);
            obj.Dispose();
            return(0);
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
コード例 #14
0
ファイル: CompressSession.cs プロジェクト: jungrok5/SpiderNET
 protected override IEnumerator ReceiveCallback(WWW www, string id)
 {
     yield return www;
     if (www.error == null)
     {
         string contentEncoding = string.Empty;
         foreach (var kvp in www.responseHeaders)
         {
             if (kvp.Key.Equals(CONTENT_ENCODING, System.StringComparison.OrdinalIgnoreCase) == true)
             {
                 contentEncoding = kvp.Key;
                 break;
             }
         }
         if (string.IsNullOrEmpty(contentEncoding) == false && www.responseHeaders[contentEncoding].Equals(ENCODING_GZIP, System.StringComparison.OrdinalIgnoreCase) == true)
         {
             using (MemoryStream inputStream = new MemoryStream())
             {
                 using (GZipInputStream zipStream = new GZipInputStream(new MemoryStream(www.bytes)))
                 {
                     byte[] buffer = new byte[4096];
                     int count = 0;
                     do
                     {
                         count = zipStream.Read(buffer, 0, www.bytes.Length);
                         inputStream.Write(buffer, 0, count);
                     } while (count != 0);
                 }
                 byte[] receiveData = inputStream.ToArray();
                 OnReceive(id, receiveData, 0, receiveData.Length);
             }
         }
         else
         {
             OnReceive(id, www.bytes, 0, www.bytes.Length);
         }
     }
     else
         OnError(id, www.error, null);
     www.Dispose();
 }
コード例 #15
0
        //This is where the actual code is executed
        //A URL where the image is stored
        private IEnumerator RealLoadImage(string url, UnityEngine.UI.Image imageView)
        {
            if (imageCashe.ContainsKey (url)) {
                if (imageView != null) {
                    imageView.sprite = imageCashe[url];
                }
            } else {
                //Call the WWW class constructor
                WWW imageURLWWW = new WWW (url);

                //Wait for the download
                yield return imageURLWWW;

                //Simple check to see if there's indeed a texture available
                if(imageURLWWW.error == null){
                    if (imageURLWWW.texture != null) {

                        //Construct a new Sprite
                        Sprite sprite = new Sprite ();

                        //Create a new sprite using the Texture2D from the url.
                        //Note that the 400 parameter is the width and height.
                        //Adjust accordingly
                        sprite = Sprite.Create (imageURLWWW.texture, new Rect (0, 0, imageURLWWW.texture.width, imageURLWWW.texture.height), Vector2.zero);
                        if(!imageCashe.ContainsKey(url))
                        {
                            imageCashe.Add (url, sprite);
                        }
                        //Assign the sprite to the Image Component
                        if (imageView != null) {
                            imageView.sprite = sprite;
                        }
                    }
                }
                imageURLWWW.Dispose ();
                imageURLWWW = null;
            }
            yield return null;
        }
コード例 #16
0
		IEnumerator CoLoadBundle(string name, string path)
		{
			DebugStr = "CoLoadBundle";
			using (WWW www = new WWW(path))
			{
				if (www == null)
				{
					Debugger.LogError(name + " bundle not exists");
					yield break;
				}

				yield return www;

				if (www.error != null)
				{
					Debugger.LogError(string.Format("Read {0} failed: {1}", path, www.error));
					yield break;
				}

				--bundleCount;
				LuaFileUtils.Instance.AddSearchBundle(name, www.assetBundle);
				www.Dispose();
			}                     
		}
コード例 #17
0
ファイル: WWWRequest.cs プロジェクト: npnf-seta/Fox-Poker
        public void Dispose(WWW www)
        {
            if (--RetryCount > 0)
            {
                //If you still need to download again
                ResetDownload();
                monoBehaviour.StartCoroutine(DownloadData());
            }
            else
            {
                dataResponse.www = www;
                dataResponse.Error = www.error;
                dataResponse.Data = www.text;
                dataResponse.Bytes = www.bytes;

                //When complete download, Whether success or failure
                if (_onResponse != null)
                {
                    _onResponse(this, dataResponse);
                    _onResponse = null;
                }
            }
            www.Dispose();
            www = null;
        }
コード例 #18
0
ファイル: HttpConnector.cs プロジェクト: BiDuc/eDriven
        /// <summary>
        /// Disposes resources on WWW
        /// </summary>
        /// <param name="response"></param>
        public static void DisposeResources(WWW response)
        {
            //if (Application.isEditor) // Edit mode
            //{
            //    Object.DestroyImmediate(response.audioClip);
            //    Object.DestroyImmediate(response.movie);
            //    Object.DestroyImmediate(response.texture);
            //}

            //else // app mode
            //{
            //    Object.Destroy(response.audioClip);
            //    Object.Destroy(response.movie);
            //    Object.Destroy(response.texture);
            //}

            response.Dispose();

            //response = null;
            //System.GC.Collect();
        }
コード例 #19
0
ファイル: CI_gui.cs プロジェクト: linuxgurugamer/CraftImport
		System.Collections.IEnumerator doUploadCraft (string craftURL)
		{
			if (craftURL != "") {

				//if (craftURL.StartsWith ("file://"))
				if (System.IO.File.Exists (craftURL)) {
					//craftURL = craftURL.Substring (7);

					if (checkMissingParts(System.IO.File.ReadAllText (craftURL))) {
						uploadErrorMessage = "Craft file must be loadable.";
						uploadErrorMessage += instructions;
						instructions = "";
						downloadState = downloadStateType.UPLOAD_ERROR;
						yield break;
					}
					EditorLogic.LoadShipFromFile (craftURL);
					ShipConstruct ship = ShipConstruction.LoadShip (craftURL);

					Log.Info ("Craft name: " + ship.shipName);

					string thumbnailPath;
					byte[] image = null;
					bool thumbnail = false;
					//	bool deleteJpg = false;
					if (pictureUrl == "") {
						Log.Info ("Capturing thumbnail");
						ThumbnailHelper.CaptureThumbnail (ship, 1024, "Screenshots", ship.shipName);
						thumbnail = true;
						jpgToDelete = true;
						pictureUrl = "file://" + FileOperations.ROOT_PATH + "Screenshots/" + ship.shipName + ".png";
					} else {
						Log.Info ("pictureUrl nonblank");
						thumbnailPath = pictureUrl;
						if (lastSelectedCraft < 0) {
							//if (pictureUrl == "") {
							//	uploadErrorMessage = "Picture URL cannot be empty";
							//	downloadState = downloadStateType.UPLOAD_ERROR;
							//	yield break;
							//
							//}


							if (!pictureUrl.StartsWith ("file://") && !UrlExists (pictureUrl, "image")) {
								uploadErrorMessage = "Picture URL is not valid";
								downloadState = downloadStateType.UPLOAD_ERROR;
								yield break;
							} else
								pictureUrl = thumbnailPath;
	
							if (pictureUrl.StartsWith ("http://imgur.com/") || pictureUrl.Length == 5) {
								string[] p = pictureUrl.Split ('/');
								pictureUrl = "[imgur]" + p.Last () + "[/imgur]";
								Log.Info ("imgur: " + pictureUrl);
								//	file = "[imgur]" + file + "[/imgur]";
							}

						}

					}
					Log.Info ("pictureUrl: " + pictureUrl);

					if (videoUrl != "" && !UrlExists (videoUrl, "video")) {
						uploadErrorMessage = "Video URL is not a valid YouTube URL";
						downloadState = downloadStateType.UPLOAD_ERROR;
						yield break;
					}

					Log.Info ("craftURL: " + craftURL);
					string craft = System.IO.File.ReadAllText (craftURL);

					JSONNode jsonuid = uid;
					JSONNode jsonpswd = pswd;
					JSONNode jsoncraft = craft;

					string url = uploadServer () + "/crafts.json";

					JSONNode n = JSON.Parse ("{}");
					n ["username"] = uid;
					n ["password"] = pswd;
					n ["craft_file"] = craft;
					if (tags != "")
						n ["tags"] = tags;
					if (style != "")
						n ["style"] = style;
					Log.Info ("pictureUrl: " + pictureUrl);
					if (pictureUrl != "") {
						if (pictureUrl.StartsWith ("file://")) {
							// If a png file, convert to jpg before uploading
							if (pictureUrl.EndsWith (".png", StringComparison.OrdinalIgnoreCase)) {
								string pngToConvert = pictureUrl.Substring (7);
								convertedJpg = pictureUrl.Substring (7, pictureUrl.Length - 10) + "jpg";
								Log.Info ("pngToconvert: " + pngToConvert);
								Log.Info ("convertedJpg: " + convertedJpg);

								ConvertToJPG (pngToConvert, convertedJpg, thisCI.configuration.backgroundcolor);
								// Delete the file if we took a snapshot of the craft using the thumbnail function
								if (thumbnail) {
									Log.Info ("deleting: " + pngToConvert);
									System.IO.FileInfo file = new System.IO.FileInfo (pngToConvert);
									file.Delete ();
								} 
								//	deleteJpg = true;
								jpgToDelete = true;
								pictureUrl = "file://" + convertedJpg;
							}
							Log.Info ("pictureUrl 2: " + pictureUrl.Substring (7));
							if (System.IO.File.Exists (pictureUrl.Substring (7))) {
								Log.Info ("pictureUrl exists");
								image = System.IO.File.ReadAllBytes (pictureUrl.Substring (7));
								if (image != null) {
									n ["image"] = System.Convert.ToBase64String (image);
								}
								// If this wasn't a thumbnail, and it was converted, delete the jpg
								// Delete it if it was a thumbnail as well
								//		if (deleteJpg) {
								//			System.IO.FileInfo file = new System.IO.FileInfo (pictureUrl.Substring (7));
								//			file.Delete ();
								//		}
							}
						} else {
							n ["picture_url"] = pictureUrl;					
						}
					}

					if (videoUrl != "")
						n ["video_url"] = videoUrl;
					if (forceNew)
						n ["force_new"] = "true";
					else {
						n ["force_new"] = "false";
						if (lastSelectedCraft >= 0)
							n ["update_existing"] = ids [lastSelectedCraft];
					}

					//if (n ["action_groups"].AsInt == 0) {
					JSONNode a = JSON.Parse ("{}");
					string hash;
					bool actionGroupSpecified = false;
					for (int i = 0; i < 16; i++) {
						Log.Info ("i: " + i.ToString () + "    [" + actionGroups [i] + "]");
						actionGroups [i] = actionGroups [i].Trim ();
						if (actionGroups [i] != "")
							actionGroupSpecified = true;
						//if (actionGroups [i] != "") 
						{
							if (i < 10) {
								hash = (i + 1).ToString ();
							} else {
								hash = fixedActions [i - 10];
							}
							a [hash] = actionGroups [i];
							Log.Info ("Adding field: hash: " + hash + "      value: " + actionGroups [i]);
						}
					}
					//}
					if (actionGroupSpecified)
						n ["action_groups"] = a.ToJSON (0);
					string ns = n.ToJSON (0);
					//Log.Info ("json:" + ns);

					Dictionary<string, string> headers = new Dictionary<string, string> ();
					headers.Add ("Content-Type", "application/json");
					var upload = new WWW (url, Encoding.ASCII.GetBytes (ns), headers);

					// Wait until the upload is done
					yield   return upload;

					instructions = "";
				
					if (!String.IsNullOrEmpty (upload.error)) {
						Log.Error ("Error uploading: " + upload.error);
						uploadErrorMessage = upload.error;
						downloadState = downloadStateType.UPLOAD_ERROR;
						yield break;
					} else {

						Log.Info ("upload.responseHeaders.Count: " + upload.responseHeaders.Count);
						if (upload.responseHeaders.Count > 0) {
							foreach (var entry in upload.responseHeaders) {
								Log.Info (entry.Key + "=" + entry.Value);
							}
						}
							
						downloadState = downloadStateType.UPLOAD_COMPLETED;
						craftURL = "";
						//instructions = upload.text + "\n" + thumbnailPath;

						//if (upload.responseHeaders.Count > 0) {
						//	for (string entry in upload.responseHeaders) {
						//		Log.Info(entry.Value + "=" + entry.Key);
						Log.Info (upload.text);
						var j = JSON.Parse (upload.text);
						if (j != null) {
							if (j ["status"].AsInt == 200) {
								instructions = "The craft file has been uploaded.\r\n\r\nA browser window is being opened where you can edit the uploaded craft";
								if (j ["image_failed_to_upload "].AsBool == true) {
									instructions += "\r\n\r\nPlease note that the image failed to upload properly due to an Imgur error,\r\n";
									instructions += "so you will need to upload an image to Imgur yourself";
								}
								string editUrl = uploadServer () + j ["edit_url"];
								openUrl (editUrl);
							} else if (j ["status"].AsInt == 409) {
								downloadState = downloadStateType.SELECT_DUP_CRAFT;
								if (j ["existing_craft"].Count == 1)
									instructions = "There is already an existing craft by that name\r\n";
								else
									instructions = "There are " + j ["existing_craft"].Count.ToString () + " existing crafts by that name\r\n";

								ids.Clear ();
								craftNames.Clear ();
								//craftUrls.Clear ();
								selectedCraft.Clear ();
								lastSelectedCraft = -1;
								for (int i = 0; i < j ["existing_craft"].Count; i++) {
									ids.Add (j ["existing_craft"] [i] ["id"]);
									craftNames.Add (j ["existing_craft"] [i] ["name"]);
									//craftUrls.Add (j ["existing_craft"] [i] ["url"]);
									selectedCraft.Add (false);
									instructions += "\r\n" + ids [i] + ": " + craftNames [i];
								}
							} else if (j ["status"].AsInt == 401) {
								instructions = "There is a userid and/or password error\r\n";
								instructions += "Please correct your userid and/or password and try again";
								downloadState = downloadStateType.UPLOAD_ERROR;

							} else if (j ["status"].AsInt == 500) {
								instructions = "An unknown error occurred:\r\n\r\n";
								instructions += j ["error"];
								instructions += "\r\n\r\nPlease contact KerbalX support for assistance";
								downloadState = downloadStateType.UPLOAD_ERROR;
							} else {
								instructions = "Unknown Error:" + j ["status"].AsInt;
								downloadState = downloadStateType.UPLOAD_ERROR;
							}
						} else {
							instructions = "An unknown server error occurred: ";
							downloadState = downloadStateType.UPLOAD_ERROR;
						}
					}
					upload.Dispose ();
					upload = null;
				} else {
					instructions = "Error";
					downloadState = downloadStateType.UPLOAD_ERROR;
				}
			}
		}
コード例 #20
0
ファイル: ResLoader.cs プロジェクト: zs9024/Jungle
        //-------------------------------------------------------------------------
        /// <summary>
        /// 读取StreamingAssets目录下本地文本文件,Android平台下要通过www类读取
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="onRead"></param>
        public static IEnumerator ReadStreamingFile(string filePath,Action<string> onRead)
        {
            string data = null;

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

            if(!string.IsNullOrEmpty(www.error))
            {
                Debug.LogWarning("ReadStreamingFile error : " + www.error);
                yield break;
            }

            data = www.text.TrimEnd();
            www.Dispose();

            if (onRead != null)
                onRead(data);

            yield return null;
        }
コード例 #21
0
        // Overriden from MonoBehaviour
        // This method processes the main request state machine
        void Update()
        {
            // If we're not already done, check for timeout
            if (State.Complete != mState && State.Finished != mState)
            {
                System.TimeSpan requestTime = System.DateTime.UtcNow - mStartTime;
                if ((int)requestTime.TotalMilliseconds > mTimeout)
                {
                    // We're out of time
                    mResult.ErrorCode = Error.RequestTimedOut;
                    mState = State.Complete;
                }
            }

            switch (mState)
            {
                case State.FetchPolicy:
                    // See http://docs.unity3d.com/Documentation/Manual/SecuritySandbox.html
                    System.Uri uri = new System.Uri(mUrl);
                    System.Net.IPAddress[] addr = System.Net.Dns.GetHostAddresses(uri.Host);
                    if (addr.Length > 0)
                    {
                        // 1024 is the port our servers listen on.  Do NOT change this unless you know what you're doing.
                        if (Security.PrefetchSocketPolicy(addr[0].ToString(), 1024))
                        {
                            // Success! Now, let's connect to the server
                            mState = State.Connect;
                        }
                        else
                        {
                            // Couldn't fetch the policy file.
                            Util.logError("Failed to fetch the policy file.");

                            // This is a problem, we're done
                            mResult.ErrorCode = Error.Generic;
                            mState = State.Complete;
                        }
                    }
                    else
                    {
                        // Couldn't resolve the Host?
                        Util.logError("Failed to resolve the host.");

                        // This is a problem, we're done...
                        mResult.ErrorCode = Error.InvalidArgs;
                        mState = State.Complete;
                    }
                    break;
                case State.Connect:
                    mState = State.ReadResponse;

                    /*
                    System.Collections.Hashtable headers = new System.Collections.Hashtable(2) {
                        { "ssf-use-positional-post-params", "true" },
                        { "ssf-contents-not-url-encoded", "true" }
                    };
                    */
                    Dictionary<string, string> headers = new Dictionary<string, string>();
                    headers.Add("ssf-use-positional-post-params", "true");
                    headers.Add("ssf-contents-not-url-encoded", "true");

                    mWWW = new WWW(mUrl, System.Text.Encoding.UTF8.GetBytes(mSendData), headers);
                    break;
                case State.ReadResponse:
                    if (mWWW.isDone)
                    {
                        mState = State.Complete;
                        if (mWWW.error != null)
                            mResult.ErrorCode = Error.Generic;
                        else
                            mResult.Response = mWWW.text;
                    }
                    break;
                case State.Complete:
                    // Perform any cleanup
                    if(null != mWWW) mWWW.Dispose();

                    // Call back the listener with the result
                    if (null != mListener)
                    {
                        mListener.onComplete(mResult);
                    }

                    // Remove ourselves...
                    GameObject.Destroy(this);

                    // Move into the finished state while we wait to be destroyed
                    mState = State.Finished;
                    break;
                case State.Finished:
                    // Waiting to be destroyed
                    break;
            }
        }
コード例 #22
0
ファイル: Connection.cs プロジェクト: moskra/Orions
		IEnumerator WaitForRequestCharacterImage(string imageUrl)
		{
			WWW www = new WWW( imageUrl );
			
			yield return www;
			if (www.error == null) {
				Debug.Log("ok");
				Texture2D temp = new Texture2D (www.texture.width, www.texture.height, TextureFormat.DXT1, false);
				www.LoadImageIntoTexture (temp as Texture2D);
				characterImage = temp;
				isLoad = true;
				www.Dispose ();
				www = null;
			}

		}
コード例 #23
0
ファイル: LoadResources.cs プロジェクト: zs9024/Jungle
        //开始异步加载AssetBundle类型的资源
        //远程下载文件到内存中成为AssetBundle镜像,再开辟内存从AssetBundle镜像中创建出指定Asset,最后卸载掉AB镜像内存,只保留Asset对象
        private static IEnumerator BeginAssetBundleLoadAsync(ResourceItem item)
        {
            var isMainifest = IsManifest(item.Path);
            var path = AssetPathConfig.GetAssetPathWWW(!isMainifest ? item.Path.ToLower() : item.Path);
            item.SetLoadState(EResItemLoadState.Loading);
            //if (item.Path.Contains("atlas")) LoggerHelper.Error("begin atlas path: " + item.Path);
            var www = new WWW(path);
            yield return www;

            if (string.IsNullOrEmpty(www.error))
            {
                item.SetLoadState(EResItemLoadState.Completed);
                //Debug.LogError("load success, path: " + www.url);

                if (!item.IsSaveAssetBundle || !IsSaveBundle(item.Path))
                {
                    Object mainAsset = null;
                    var bundle = www.assetBundle;
                    if (isMainifest)
                    {
                        //LoggerHelper.Error("is mainifest: " + item.Path);
                        mainAsset = bundle.LoadAsset("AssetBundleManifest");
                        item.SetMainAsset(mainAsset);
                    }
                    else
                    {
                        mainAsset = bundle.mainAsset;
                        if (mainAsset == null)
                        {
                            var assets = bundle.LoadAllAssets();
                            if (assets == null || assets.Length == 0)
                            {
                                Debug.LogError("load no assets, path: " + item.Path);
                                yield break;
                            }
                            mainAsset = assets[0];

                            item.SetMainAsset(mainAsset);
                            item.SetAssets(assets);
                        }
                    }

                    item.LaunchCallBack();

                    if (bundle != null)
                        bundle.Unload(false);

                    www.Dispose();
                }
                else
                {
                    item.SetAssetBundle(www.assetBundle);
                    //if (item.Path.StartsWith("atlas")) LoggerHelper.Error("after atlas path: " + item.Path);
                    item.LaunchCallBack();
                    www.Dispose();
                }
            }
            else
            {
                item.SetLoadState(EResItemLoadState.Error);
                Debug.LogError(string.Format("加载资源失败:{0}\n{1}", www.url, www.error));
                item.LaunchCallBack();
            }

            //按需清除ResourceItem缓存
            if (item.IsClearAfterLoaded)
            {
                Clear(item.Path);
                GarbageCollect();
            }
        }
コード例 #24
0
        private StatErrorData analyzeAssetBundle(string assetPath)
        {
            if (!IsOKSuffix(Path.GetExtension(assetPath)))
                return null;

            StatErrorData data = new StatErrorData();
            data.filename = assetPath;
			WWW www = null;

            try
            {
                string escName = WWW.EscapeURL("file:///" + assetPath);
                Debug.Log(escName);

                LogData = data;

                Application.RegisterLogCallback(HandleLog);

                www = new WWW("file:///" + assetPath);
                //WWW www = WWW.LoadFromCacheOrDownload("file:///" + assetPath, 0);

                if (!string.IsNullOrEmpty(www.error))
                {
                    data.errortext = www.error;

                }
                else
                {
                    data.errortext = "no error";

                    if (deeply &&
                        www.assetBundle != null)
                    {
                        Object[] loadedObjects = www.assetBundle.LoadAll();
                        if (loadedObjects == null)
                            data.errortext = "all = null";

                        if (!string.IsNullOrEmpty(www.error))
                        {
                            data.errortext = www.error;
                        }
                    }
                }
            }
            catch (System.Exception e)
            {
                data.errortext = e.Message;
            }

			if (www.assetBundle != null)
				www.assetBundle.Unload(true);
			
			www.Dispose();

            Application.RegisterLogCallback(null);
            LogData = null;
            

            return data;
        }
コード例 #25
0
        IEnumerator StartTimeout(WWW www, float time)
        {
            yield return new WaitForSeconds(time);

            if (!www.isDone)
            {
                www.Dispose();
                _disposed.Add(www);
            }
        }
コード例 #26
0
ファイル: LoadResources.cs プロジェクト: zs9024/Jungle
        /// <summary>
        /// WWW加载图片
        /// </summary>
        /// <param name="callback"></param>
        /// <returns></returns>
        private static IEnumerator BeginImageLoadAsync(ResourceItem item, string savePath)
        {
            item.SetLoadState(EResItemLoadState.Loading);
            string path = item.Path;
            var www = new WWW(path);
            yield return www;

            //Debug.LogError("LoadImage save good: " + savePath);

            if (string.IsNullOrEmpty(www.error))
            {
                var texture2d = www.texture;
                texture2d.Compress(true);
                item.SetLoadState(EResItemLoadState.Completed);
                item.SetMainAsset(texture2d);
                item.LaunchCallBack();

                try
                {
                    File.WriteAllBytes(savePath, www.bytes);
                }
                catch (Exception e)
                {
                    Debug.LogError("LoadImage save error: " + e.ToString());
                }

                www.Dispose();
            }
            else
            {
                //Debug.LogError("pp: " + path);
                item.SetLoadState(EResItemLoadState.Error);
                Debug.LogError(string.Format("加载资源失败:{0}\n{1}", www.url, www.error));
                item.LaunchCallBack();
            }

            //按需清除ResourceItem缓存
            if (item.IsClearAfterLoaded)
            {
                Clear(item.Path);
                GarbageCollect();
            }
        }
コード例 #27
0
        /// <summary>
        /// Downloads an image at the given URL and converts it to a Unity Texture2D.
        /// </summary>
        /// <param name="url">The URL of the image to download.</param>
        /// <returns>The image as a Unity Texture2D object.</returns>
        public static Texture2D DownloadImage(string url)
        {
            bool timedout = false;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            WWW request = new WWW(url);
            while (!request.isDone)
            {
                if (stopwatch.ElapsedMilliseconds >= 750)
                {
                    //LogVerbose("Downloading image timed out! Took more than 750ms.");

                    request.Dispose();
                    stopwatch.Stop();
                    timedout = true;
                    break;
                }
            }

            if (!timedout && !string.IsNullOrEmpty(request.error))
            {
                LogVerbose(request.error);
            }

            Texture2D result = null;

            if (!timedout && string.IsNullOrEmpty(request.error))
            {
                result = request.texture;
            }

            return result;
        }
コード例 #28
0
        private void LoadExternalCoroutine(string name, UIImage image)
        {
            string url = "file://" + GameManager.Instance.mainGame.ExternalResourcePath + "/" + name + ".jpg";
            Debug.Log(name);
            WWW www = new WWW(url);

            if (string.IsNullOrEmpty(www.error))
            {
             				www.LoadImageIntoTexture(loaderTexture);

                Sprite sprite = Sprite.Create(loaderTexture,
                    new Rect(0, 0, loaderTexture.width, loaderTexture.height),
                    // new Rect(0, 0, www.texture.width, www.texture.height),  //->this eat up memory!!
                    new Vector2(0.5f, 0.5f), 100.0f);

                Sprite[] sprites = new Sprite[1];
                sprites[0] = sprite;
                image.SetSprites(sprites);
                image.Sprite = 0;

                DestroyImmediate(www.texture);

            }
            else
            {
                Debug.LogWarning(www.error);

                image.SetSprites(UIManager.LoadSprite(name));
                image.Sprite = 0;
            }

            www.Dispose();
            www = null;
        }
コード例 #29
0
ファイル: AudioLoader.cs プロジェクト: hjrhjr/Beats2
        /// <summary>
        /// Loads a base <see cref="AudioClip"/> from disk
        /// </summary>
        /// <returns>
        /// A base <see cref="AudioClip"/>
        /// </returns>
        /// <param name='path'>
        /// Path to audio file
        /// </param>
        /// <param name='stream'>
        /// Whether or not the <see cref="AudioClip"/> should be fully loaded into memory or streamed from disk
        /// </param>
        private static AudioClip LoadAudioClip(string path, bool stream)
        {
            string filePath = SysPath.FindFile(path, SysPath.AudioExtensions);
            if (filePath == null) {
                Logger.Error(TAG, String.Format("Unable to find audio file: \"{0}\"", path));
                return null;
            }

            string url = SysPath.GetWwwPath(filePath);
            WWW www = new WWW(url);
            //while (!www.isDone); // FIXME: Is blocking here necessary?

            AudioClip clip;
            clip = www.GetAudioClip(false, stream);
            while(!clip.isReadyToPlay); // Wait for buffer
            www.Dispose(); // FIXME: What does this even do? Documentation is blank...

            if (clip == null) {
                Logger.Error(TAG, String.Format("Unable to load audio file: \"{0}\"", url));
            }
            return clip;
        }
コード例 #30
0
        private IEnumerator Process(WWW www)
        {
            yield return www;

            if(www.error == null)
            {
                if (www.responseHeaders.ContainsKey("STATUS"))
                {
                    //LOG Google analitic
                    if (www.responseHeaders["STATUS"] == "HTTP/1.1 200 OK")
                    {
                        //Debug.Log ("GA Success");
                    } else {
                        //Debug.LogWarning(www.responseHeaders["STATUS"]);
                    }
                }else{
                    Debug.LogWarning("Event failed to send to Google");
                }
            }else{
                Debug.LogWarning(www.error.ToString());
            }

            www.Dispose();
        }
コード例 #31
0
ファイル: HttpClient.cs プロジェクト: Naphier/NGTools
        public IEnumerator ExecuteCoroutine()
        {
            busy = true;
            attempts++;
            www = GetWWW();

            bool failed = false;
            while (!www.isDone)
            {
                yield return null;

                result.timeElapsed = Time.time - startTime;

                if (_cancel ||
                    timeOut > 0f && ((result.timeElapsed) > timeOut))
                {
                    if (_cancel)
                    {
                        result.error = StatusMessage.Canceled(host);
                        result.statusCode = StatusCode.CANCELED;
                    }
                    else
                    {
                        result.error = StatusMessage.TimeOut(result.timeElapsed, host);
                        result.statusCode = StatusCode.TIMEOUT;
                    }

                    result.isError = true;
                    result.isSuccess = false;
                    failed = true;
                    disposed = true;
                    www.Dispose();
                    break;
                }
            }

            if (!failed)
            {
                if (string.IsNullOrEmpty(www.error))
                {
                    HandleSuccess(result, www);
                }
                else
                {
                    failed = true;
                }
            }

            if (failed)
                HandleError(result, www);

            busy = false;

            _canBeDestroyed = true;

            if (failed && attempts < retryAttempts)
            {
                _canBeDestroyed = false;
                www = null;
                yield return new WaitForSeconds(delayBetweenRetries);
                startTime = Time.time;
                wwc.Execute();
            }
            else
            {
                if (onFinished != null)
                    onFinished(result);
            }
        }
コード例 #32
0
        // check vive input utility version on github
        private static void CheckVersionAndSettings()
        {
            if (Application.isPlaying)
            {
                EditorApplication.update -= CheckVersionAndSettings;
                editorUpdateRegistered    = false;
                return;
            }

            InitializeSettins();

            // fetch new version info from github release site
            if (!completeCheckVersionFlow && VIUSettings.autoCheckNewVIUVersion)
            {
                if (webReq == null) // web request not running
                {
                    if (EditorPrefs.HasKey(nextVersionCheckTimeKey) && DateTime.UtcNow < UtcDateTimeFromStr(EditorPrefs.GetString(nextVersionCheckTimeKey)))
                    {
                        VersionCheckLog("Skipped");
                        completeCheckVersionFlow = true;
                        return;
                    }

                    webReq = GetUnityWebRequestAndSend(lastestVersionUrl);
                }

                if (!webReq.isDone)
                {
                    return;
                }

                // On Windows, PlaterSetting is stored at \HKEY_CURRENT_USER\Software\Unity Technologies\Unity Editor 5.x
                EditorPrefs.SetString(nextVersionCheckTimeKey, UtcDateTimeToStr(DateTime.UtcNow.AddMinutes(versionCheckIntervalMinutes)));

                if (UrlSuccess(webReq))
                {
                    var json = GetWebText(webReq);
                    if (!string.IsNullOrEmpty(json))
                    {
                        latestRepoInfo = JsonUtility.FromJson <RepoInfo>(json);
                        VersionCheckLog("Fetched");
                    }
                }

                // parse latestVersion and ignoreThisVersionKey
                if (!string.IsNullOrEmpty(latestRepoInfo.tag_name))
                {
                    try
                    {
                        latestVersion        = new System.Version(Regex.Replace(latestRepoInfo.tag_name, "[^0-9\\.]", string.Empty));
                        ignoreThisVersionKey = string.Format(fmtIgnoreUpdateKey, latestVersion.ToString());
                    }
                    catch
                    {
                        latestVersion        = default(System.Version);
                        ignoreThisVersionKey = string.Empty;
                    }
                }

                webReq.Dispose();
                webReq = null;

                completeCheckVersionFlow = true;
            }

            VIUSettingsEditor.PackageManagerHelper.PreparePackageList();
            if (VIUSettingsEditor.PackageManagerHelper.isPreparingList)
            {
                return;
            }

            showNewVersion = !string.IsNullOrEmpty(ignoreThisVersionKey) && !VIUProjectSettings.HasIgnoreKey(ignoreThisVersionKey) && latestVersion > VIUVersion.current;

            UpdateIgnoredNotifiedSettingsCount(false);

            if (showNewVersion || notifiedSettingsCount > 0)
            {
                TryOpenRecommendedSettingWindow();
            }

            EditorApplication.update -= CheckVersionAndSettings;
            editorUpdateRegistered    = false;
        }
コード例 #33
0
ファイル: Cache.cs プロジェクト: tenvick/hugula
        /// <summary>
        /// Adds the source cache data from WW.
        /// </summary>
        /// <param name="www">Www.</param>
        /// <param name="req">Req.</param>
        internal static bool AddSourceCacheDataFromWWW(WWW www, CRequest req)
        {
            object data = null;
            var ab = www.assetBundle;
            req.isAssetBundle = false;

            if (ab != null) {
                data = ab;
                req.isAssetBundle = true;
                CacheData cacheData = new CacheData (data, null, req.key);//缓存
                CacheManager.AddCache (cacheData);
                cacheData.allDependencies = req.allDependencies;
                cacheData.assetBundle = ab;

            } else if (Typeof_String.Equals (req.assetType)) {
                req.data = www.text;
            }
            else if(Typeof_AudioClip.Equals(req.assetType)) {
                req.data = www.audioClip;
            }else if(Typeof_Texture2D.Equals(req.assetType) ) {
                if (req.assetName.Equals ("textureNonReadable"))
                    req.data = www.textureNonReadable;
                else
                    req.data = www.texture;
            }

            if (Typeof_Bytes.Equals (req.assetType)) {
                req.data = www.bytes;
                req.isAssetBundle = false;
            }

            req.uris.OnWWWComplete (req, www);
            www.Dispose();

            return req.isAssetBundle;
        }
コード例 #34
0
 private void ImageOrig()
 {
     _imagetex = new WWW(_imageurl + _imagefile);
     _image = _imagetex.texture;
     _imagetex.Dispose();
     GUI.DrawTexture(new Rect(0f, 20f, _image.width, _image.height), _image, ScaleMode.ScaleToFit, true, 0f);
 }
		IEnumerator LoadExternalCoroutine(string name, UIVideo video)
		{
			//load only once
			string url = "file://" + GameManager.Instance.mainGame.ExternalResourcePath + "/" + name + ".ogv";
			// Debug.Log(">>>>>>> Load file:" + url);
			//WebPlayerDebugManager.addOutput("_______ LoadExternalCoroutine url: "+url, 1);

			//release resources for www
			DestroyImmediate(video.movie);
			DestroyImmediate(video.GameObject.GetComponent<Renderer>().material.mainTexture);
			video.movie = null;

			WWW www = new WWW(url);

			// while (!www.movie.isReadyToPlay);

			yield return www;
			
			if (string.IsNullOrEmpty(www.error))
			{
				video.movie = www.movie;
				video.GameObject.GetComponent<Renderer>().material.mainTexture = video.movie;
				video.GameObject.GetComponent<Renderer>().material.color = Color.white;
				video.movie.Play(); //hack: get the first frame
				video.movie.Stop();
			}
			else
			{
				Debug.LogWarning(www.error);
				MovieTexture t = Resources.Load<MovieTexture>(name);
				if (t != null)
				{
					video.movie = t;
					video.GameObject.GetComponent<Renderer>().material.mainTexture = video.movie;
				}
			}

			www.Dispose();
			www = null;
		}
コード例 #36
0
 private void Update()
 {
     if (Input.GetKey(KeyCode.LeftAlt) && Input.GetKeyDown(_keybind))
     {
         Toggle();
     }
     if (Input.GetKey(KeyCode.LeftControl) && Input.GetKeyDown(_keybind))
     {
         _showList = !_showList;
     }
     if (_imageList == null) return;
     if (_lastimg == _selectionGridInt) return;
     Destroy(_image);
     _imagefile = _imageList[_selectionGridInt];
     _imagetex = new WWW(_imageurl + _imagefile);
     _image = _imagetex.texture;
     _imagetex.Dispose();
     _lastimg = _selectionGridInt;
 }