public override IEnumerator DownLoad() { // Check fatal if (LoadState != EWebLoadState.None) { throw new Exception($"Web file download state is not none state. {URL}"); } LoadState = EWebLoadState.Loading; // 下载文件 CacheRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbGET); DownloadHandlerFile handler = new DownloadHandlerFile(SavePath); handler.removeFileOnAbort = true; CacheRequest.downloadHandler = handler; CacheRequest.disposeDownloadHandlerOnDispose = true; CacheRequest.timeout = ResDefine.WebRequestTimeout; yield return(CacheRequest.SendWebRequest()); // Check error if (CacheRequest.isNetworkError || CacheRequest.isHttpError) { LogSystem.Log(ELogType.Warning, $"Failed to download web file : {URL} Error : {CacheRequest.error}"); LoadState = EWebLoadState.LoadFailed; } else { LoadState = EWebLoadState.LoadSucceed; } // Invoke callback LoadCallback?.Invoke(this); }
public override void Update() { if (IsDone()) { return; } if (LoadState == EAssetFileLoadState.None) { LoadState = EAssetFileLoadState.LoadAssetFile; } // 1. 加载主资源对象 if (LoadState == EAssetFileLoadState.LoadAssetFile) { // Load resource folder file System.Type systemType = AssetSystem.MakeSystemType(AssetType); if (systemType == null) { _cacheRequest = Resources.LoadAsync(LoadPath); } else { _cacheRequest = Resources.LoadAsync(LoadPath, systemType); } LoadState = EAssetFileLoadState.CheckAssetFile; } // 2. 检测AssetObject加载结果 if (LoadState == EAssetFileLoadState.CheckAssetFile) { if (_cacheRequest.isDone == false) { return; } _mainAsset = _cacheRequest.asset; // Check scene if (AssetType == EAssetType.Scene) { LoadState = EAssetFileLoadState.LoadAssetFileOK; LoadCallback?.Invoke(this); return; } // Check error if (_mainAsset == null) { LogSystem.Log(ELogType.Warning, $"Failed to load resource file : {LoadPath}"); LoadState = EAssetFileLoadState.LoadAssetFileFailed; LoadCallback?.Invoke(this); } else { LoadState = EAssetFileLoadState.LoadAssetFileOK; LoadCallback?.Invoke(this); } } }
internal LoadReturnArgs(AssetBundleFeature feature, long taskid) { _cacheFeature = feature; TaskId = taskid; _loadCallback = null; _progressEvent = null; }
/// <summary> /// 移除加载回调 /// </summary> /// <param name="url"></param> /// <param name="completeCallback"></param> /// <param name="progressCallback"></param> /// <param name="errorCallback"></param> public void RemoveLoadCallbackImmediately(string url, LoadCallback completeCallback = null, LoadCallback progressCallback = null, LoadCallback errorCallback = null) { LoadItem item; if (_immediateDict.TryGetValue(url, out item) == false) { return; } // 移除加载完成回调 if (completeCallback != null) { item.completeCallback -= completeCallback; } // 移除加载进度回调 if (progressCallback != null) { item.progressCallback -= progressCallback; } // 移除加载失败回调 if (errorCallback != null) { item.errorCallback -= errorCallback; } // 如果加载项已经不存在加载回调,则关闭加载 if (item.isLoading == false && item.completeCallback == null) { StopLoad(item); } }
public LoadReturnArgs SetCallBack(LoadCallback value) { if (_loadCallback != value) { _loadCallback = value; if (_cacheFeature != null) { var contexts = _cacheFeature.StartRead(); if (contexts.Tasks != null) { for (int i = 0; i < contexts.Tasks.Count; i++) { var task = contexts.Tasks[i]; if (task.TaskId == this.TaskId) { task.Result.ResultCallback = value; contexts.Tasks[i] = task; _cacheFeature.EndRead(ref contexts); break; } } } } else { Debug.LogError("cant bind callback"); } } return(this); }
protected override void OnEdgeStateChanged(Rect oldState, Rect state) { base.OnEdgeStateChanged(oldState, state); if (oldState.Top != state.Top) { if (null != OnLoadStateChangedListener) { OnLoadStateChangedListener.OnRefreshStateChanged(this, oldState.Top, state.Top); } if (state.Top == EDGE_STATE_LOADING) { OnRefresh(); if (null != LoadCallback) { LoadCallback.OnRefresh(this); } } } if (oldState.Bottom != state.Bottom) { if (null != OnLoadStateChangedListener) { OnLoadStateChangedListener.OnLoadMoreStateChanged(this, oldState.Bottom, state.Bottom); } if (state.Bottom == EDGE_STATE_LOADING) { OnLoadMore(); if (null != LoadCallback) { LoadCallback.OnLoadMore(this); } } } }
public ImageLoader(string path, string key, LoadCallback callback, FinishCallback finishCallback) { _path = path; _key = key; _callback = callback; _finishCallback = finishCallback; }
public Operation(string path, int version, string[] names, LoadCallback callback) { this.path = path; this.version = version; this.names = names; this.callback = callback; }
public bool LoadResourceAsync(string name, LoadCallback cbFunc, bool save = true) { Object obj = GetResource(name, false); if (obj != null) { if (cbFunc != null) { cbFunc(name, obj); } return(true); } ResourceRequest req = Resources.LoadAsync(name); if (save && req.asset != null) { m_Objects[name] = req.asset; } if (cbFunc != null) { cbFunc(name, req.asset); } return(true); }
// 预加载基础资源 public void PreLoad(LoadCallback callback) { Object asset = LoadResource("preload", false); if (asset == null) { return; } TextAsset textAsset = (TextAsset)asset; LitJson.JsonReader jsonR = new LitJson.JsonReader(textAsset.text); LitJson.JsonData jsonD = LitJson.JsonMapper.ToObject(jsonR); if (!jsonD.IsArray || jsonD.Count == 0) { return; } // 逐个加载资源,全部加载完毕后执行回调函数 for (int i = 0; i < jsonD.Count; i++) { LoadResource((string)jsonD[i]["name"], true); } if (callback != null) { callback(null, null); } }
/// <summary> /// 在游戏过程中的加载【需要预防:加载完后回调已经被删除】 /// 可以用于loading过程,也能用于游戏过程,可以选择是否缓存 /// </summary> /// <param name="name"></param> /// <param name="_callback"></param> /// <param name="noCache"></param> public void loadWeak(string name, LoadCallback _callback, bool cache) { //确认cache sCacheUnit scu = sCache.GetInstance().getUnusedCache(name); if (scu != null) { scu.isUsing = true; if (_callback != null) { if (sCache.GetInstance().isLoadOK(name)) { _callback(scu); } else { sCache.GetInstance().pushCache(name, _callback); } } return; } //如果cache无法解决,则读取资源(需要先创建一个scu,用于确保下次读取时不用重复加载) sCache.GetInstance().initPreCache(CacheType.single, name, !cache); sCache.GetInstance().pushCache(name, _callback); sLoadAssetbundle.GetInstance().loadAssetBundle(name, (obj) => { sCache.GetInstance().cacheLoadOK(name, obj); }); }
public void Load <T>(string key, LoadCallback <T> cb) where T : IMessage { uint dsMsgId = MessageMapping.Query(typeof(T)); if (dsMsgId == uint.MaxValue) { cb(DSLoadResult.PrepError, string.Format("unknown data message: {0}", typeof(T).Name), default(T)); return; } string timeoutKey = string.Format("{0}:{1}", dsMsgId, key); if (loadOpt_timeout_.Exists(timeoutKey)) { cb(DSLoadResult.PrepError, "Load operation are too frequent", default(T)); } else { LNReq_Load.Builder loadBuilder = LNReq_Load.CreateBuilder(); loadBuilder.SetDsMsgId(dsMsgId); loadBuilder.SetKey(key); LNReq_Load loadData = loadBuilder.Build(); if (!channel_.Send(loadData)) { cb(DSLoadResult.PrepError, "Create protobuf data error.", default(T)); } else { LoadCBBox cbbox = new LoadCBBoxI <T>(cb); string timeoutTip = string.Format("DataStore load request timeout. MsgId:{0}, Key:{1}", dsMsgId, key); loadOpt_timeout_.Set(timeoutKey, cbbox, () => cbbox.Invoke(DSLoadResult.TimeoutError, timeoutTip, null)); } } }
protected virtual void LoadAssetAsync <T>(AssetCacheType AssetType, string AssetPath, Action <bool> Callback = null) where T : UnityEngine.Object { AssetPath = AssetPath.ToLower(); if (AssetCacheExisted(AssetPath)) { Callback?.Invoke(true); return; } if (!AssetLoadCallbackList_.ContainsKey(AssetPath)) { AssetLoadCallbackList_.Add(AssetPath, new List <Action <bool> > { Callback }); LoadAssetCacheCompletedAsync <T>(AssetType, AssetPath, (IsLoaded) => { foreach (var LoadCallback in AssetLoadCallbackList_[AssetPath]) { LoadCallback?.Invoke(IsLoaded); } AssetLoadCallbackList_.Remove(AssetPath); }); } else { AssetLoadCallbackList_[AssetPath].Add(Callback); } }
public void LoadFromFileAndHide() { Deck newDeck = Deck.Parse(CardGameManager.Current, DeckFiles[SelectedFilePath], CardGameManager.Current.DeckFileType, GetDeckText()); LoadCallback?.Invoke(newDeck); Hide(); }
/// <summary> /// Add a section to the save files with the specified callbacks for /// retrieving values to be saved and notifying the mod of loaded values. /// </summary> /// <param name="title">Title of the section</param> /// <param name="saveCb">Callback for saving</param> /// <param name="loadCb">Callback for loading</param> public static void Add(string title, SaveCallback saveCb, LoadCallback loadCb) { metadata.Add(title, new Metadata() { saveCb = saveCb, loadCb = loadCb, }); }
public override ExpressionDrawer.IDrawable Load(MemoryReader mreader, Debugger debugger, string name, string type, LoadCallback callback) { // NOTE: If the image is not created at the point of debugging, so the variable is // uninitialized, the size may be out of bounds of int32 range. In this case the // exception is thrown here and this is ok. However if there is some garbage in // memory random size could be loaded here. Then also the memory probably points // to some random place in memory (maybe protected?) so the result will probably // be another exception which is fine or an image containing noise from memory. ulong dataStart = ExpressionParser.GetPointer(debugger, name + ".DataStart"); ulong dataEnd = ExpressionParser.GetPointer(debugger, name + ".DataEnd"); ulong length = dataEnd - dataStart; int cols = ExpressionParser.LoadSize(debugger, name + ".Cols"); int rows = ExpressionParser.LoadSize(debugger, name + ".Rows"); EnvDTE.Expression exp = debugger.GetExpression("(int)(" + name + ".Type())"); MatType mType = MatType.CV_8UC1; if (exp.IsValidValue) { mType = (MatType)int.Parse(exp.Value); } byte[] memory = new byte[length]; bool isLoaded = false; if (mreader != null) { ulong address = ExpressionParser.GetValueAddress(debugger, name + ".DataPointer[0]"); if (address == 0) { return(null); } isLoaded = mreader.ReadBytes(address, memory); } var pixelFormat = MatTypeToPixelFormat(mType); Bitmap bmp = new Bitmap( cols, rows, pixelFormat); BitmapData data = bmp.LockBits( new Rectangle(System.Drawing.Point.Empty, bmp.Size), ImageLockMode.WriteOnly, pixelFormat); Marshal.Copy(memory, 0, data.Scan0, (int)length); bmp.UnlockBits(data); return(new ExpressionDrawer.Image(bmp)); }
void Awake() { checkpointDirectory = Application.dataPath; tempDirectory = Application.temporaryCachePath; preSaveCallback = delegate { }; postLoadCallback = delegate { }; Debug.Log("Checkpoint Directory: " + checkpointDirectory); Debug.Log("Temp Directory: " + tempDirectory); }
public override void Update() { #if UNITY_EDITOR if (IsDone()) { return; } if (LoadState == EAssetFileLoadState.None) { LoadState = EAssetFileLoadState.LoadAssetFile; } // 1. 加载主资源对象 if (LoadState == EAssetFileLoadState.LoadAssetFile) { // Load from database System.Type systemType = AssetSystem.MakeSystemType(AssetType); string assetPath = GetDatabaseAssetPath(LoadPath); _mainAsset = UnityEditor.AssetDatabase.LoadAssetAtPath(assetPath, systemType); LoadState = EAssetFileLoadState.CheckAssetFile; // 注意:为了模拟异步加载效果,这里直接返回 return; } // 2. 检测AssetObject加载结果 if (LoadState == EAssetFileLoadState.CheckAssetFile) { // Check scene if (AssetType == EAssetType.Scene) { LoadState = EAssetFileLoadState.LoadAssetFileOK; LoadCallback?.Invoke(this); return; } // Check error if (_mainAsset == null) { LogSystem.Log(ELogType.Warning, $"Failed to load database file : {LoadPath}"); LoadState = EAssetFileLoadState.LoadAssetFileFailed; LoadCallback?.Invoke(this); } else { LoadState = EAssetFileLoadState.LoadAssetFileOK; LoadCallback?.Invoke(this); } } #else throw new Exception("AssetDatabaseLoader only support unity editor."); #endif }
/// <see cref="ISmartLockCredentialsImpl.Save"/> public void Save(ICredential credential, Action <Status, ICredential> callback) { AndroidJavaClass supportClass = GetSupportClass(); if (supportClass == null) { Debug.LogError("Cannot load java support class: " + SupportActivityClassname); callback(Status.Error, null); return; } AndroidJavaObject unityActivity = GetUnityActivity(); if (unityActivity == null) { Debug.LogError("Cannot get Unity player activity"); callback(Status.Error, null); return; } IntPtr methodId = AndroidJNI.GetStaticMethodID(supportClass.GetRawClass(), "doSave", "(Landroid/app/Activity;" + "Lcom/google/smartlocksupport/SmartLockSupportResponseHandler;" + "Ljava/lang/String;" + "Ljava/lang/String;" + "Ljava/lang/String;" + "Ljava/lang/String;" + "Ljava/lang/String;)V"); if (methodId.Equals(IntPtr.Zero)) { Debug.LogError("Cannot find method doSave in java support class"); callback(Status.Error, null); return; } object[] objectArray = new object[7]; jvalue[] jArgs; LoadCallback cb = new LoadCallback(callback); objectArray[0] = unityActivity; objectArray[1] = cb; objectArray[2] = credential.ID; objectArray[3] = credential.Password; objectArray[4] = credential.AccountType; objectArray[5] = credential.Name; objectArray[6] = credential.ProfilePictureURL; jArgs = AndroidJNIHelper.CreateJNIArgArray(objectArray); AndroidJNI.CallStaticVoidMethod(supportClass.GetRawClass(), methodId, jArgs); Debug.Log("Done calling doSave"); }
/// <summary> /// 加载资源 /// </summary> /// <param name="url"></param> /// <param name="id"></param> /// <param name="type"></param> /// <param name="priority"></param> /// <param name="completeCallback"></param> /// <param name="progressCallback"></param> /// <param name="errorCallback"></param> /// <param name="save"></param> /// <param name="cache"></param> /// <param name="loadImmediately"></param> /// <returns></returns> public LoadItem Load(string url, string id, LoadType type = LoadType.AUTO, LoadPriority priority = LoadPriority.LV_2, LoadCallback completeCallback = null, LoadCallback progressCallback = null, LoadCallback errorCallback = null, bool save = true, bool cache = true, bool loadImmediately = false) { // 创建加载项 LoadItem item = new LoadItem(url, id, type, priority, save, cache); item.completeCallback = completeCallback; item.progressCallback = progressCallback; item.errorCallback = errorCallback; return(Load(item)); }
public static void GetObject(string path, int version, string[] names, LoadCallback callback) { if (manager == null) { if (callback != null) { callback(null); } return; } manager.LoadObject(path, version, names, callback); }
//加载关卡 public static void LoadLevel(string strScene, LoadCallback cb, object param) { LoadLevelSync(strScene); if (cb != null) { ResMng.LoadCallBackParam pa = param as ResMng.LoadCallBackParam; if (pa != null) { pa.bLoadDone = true; } cb(param as object); } }
private IEnumerator LoadSceneBundle(string name, LoadCallback loadHandler, params object[] args) { AsyncOperation async = SceneManager.LoadSceneAsync(name); yield return async; Resources.UnloadUnusedAssets(); GC.Collect(); if (loadHandler != null) { loadHandler(args); } }
public async void LoadAsync(LoadCallback callback) { string directory = Potree.DataDirectory + SubDirectory + FileNamePrefix + Root.LocalName + Constants.HrcExt; byte[] rawData; using (var stream = new FileStream(directory, FileMode.Open, FileAccess.Read)) { rawData = new byte[stream.Length]; await stream.ReadAsync(rawData, 0, (int)stream.Length); } parseRawData(rawData); callback(this); }
private IEnumerator loadGameObject(string assetBundle, LoadCallback callback) { if (gos.ContainsKey(assetBundle)) { callback(GameObject.Instantiate(gos [assetBundle])); } else { List <LoadCallback> list; if (gocallback.ContainsKey(assetBundle)) { list = gocallback [assetBundle]; } else { list = new List <LoadCallback> (); gocallback [assetBundle] = list; } list.Add(callback); if (!goWWW.ContainsKey(assetBundle)) { string uri = @"file:///" + path + "/" + assetBundle; WWW www = new WWW(uri); goWWW [assetBundle] = www; yield return(www); var ab = www.assetBundle; var abr = ab.LoadAllAssetsAsync(); yield return(abr); GameObject role = abr.allAssets [0] as GameObject; gos [assetBundle] = role; if (gocallback.ContainsKey(assetBundle)) { List <LoadCallback> lis = gocallback [assetBundle]; foreach (var call in lis) { call(GameObject.Instantiate(role)); } lis.Clear(); gocallback.Remove(assetBundle); } goWWW.Remove(assetBundle); www.Dispose(); ab.Unload(false); } } }
/// <see cref="ISmartLockCredentialsImpl.Delete"/> public void Delete(ICredential credential, Action<Status, ICredential> callback) { AndroidJavaClass supportClass = GetSupportClass(); if (supportClass == null) { Debug.LogError("Cannot load java support class: " + SupportActivityClassname); callback(Status.Error, null); return; } AndroidJavaObject unityActivity = GetUnityActivity(); if (unityActivity == null) { Debug.LogError("Cannot get Unity player activity"); callback(Status.Error, null); return; } IntPtr methodId = AndroidJNI.GetStaticMethodID(supportClass.GetRawClass(), "doDelete", "(Landroid/app/Activity;" + "Lcom/google/smartlocksupport/SmartLockSupportResponseHandler;" + "Ljava/lang/String;" + "Ljava/lang/String;" + "Ljava/lang/String;)V"); if (methodId.Equals(IntPtr.Zero)) { Debug.LogError("Cannot find method doDelete in java support class"); callback(Status.Error, null); return; } object[] objectArray = new object[5]; jvalue[] jArgs; LoadCallback cb = new LoadCallback(callback); objectArray[0] = unityActivity; objectArray[1] = cb; objectArray[2] = credential.ID; objectArray[3] = credential.Password; objectArray[4] = credential.AccountType; jArgs = AndroidJNIHelper.CreateJNIArgArray(objectArray); AndroidJNI.CallStaticVoidMethod(supportClass.GetRawClass(), methodId, jArgs); Debug.Log("Done calling doDelete"); }
public bool LoadLuaSession(string path) { var file = new FileInfo(path); if (file.Exists) { Clear(); using (var sr = file.OpenText()) { string line; while ((line = sr.ReadLine()) != null) { if (line.StartsWith("---")) { Add(LuaFile.SeparatorInstance); } else { var scriptPath = line.Substring(2, line.Length - 2); if (!Path.IsPathRooted(scriptPath)) { var directory = Path.GetDirectoryName(path); scriptPath = Path.GetFullPath(Path.Combine(directory, scriptPath)); } Add(new LuaFile(scriptPath) { State = !Global.Config.DisableLuaScriptsOnLoad && line.Substring(0, 1) == "1" ? LuaFile.RunState.Running : LuaFile.RunState.Disabled }); } } } Global.Config.RecentLuaSession.Add(path); ForEach(lua => Global.Config.RecentLua.Add(lua.Path)); _filename = path; LoadCallback?.Invoke(); return(true); } return(false); }
public static void loadAsset <T>(string strAsset, LoadCallback <T> callback) { Addressables.LoadAssetAsync <T>(strAsset).Completed += (op) => { if (op.Result == null) { Debug.LogError(string.Format("asset : {0} is not exist", strAsset)); return; } if (callback != null) { callback(op.Result); callback = null; } }; }
public static void LoadFullTweet(long id, LoadCallback callback) { TwitterAccount.CurrentAccount.Download("http://api.twitter.com/1/statuses/show.json?id=" + id, result => { if (result == null) { callback(null); } var tweet = Tweet.ParseTweet(result); if (tweet == null) { callback(null); } callback(tweet); }); }
public override IEnumerator DownLoad() { // Check fatal if (string.IsNullOrEmpty(PostContent)) { throw new Exception($"Web post content is null or empty. {URL}"); } // Check fatal if (LoadState != EWebLoadState.None) { throw new Exception($"Web post download state is not none state. {URL}"); } LoadState = EWebLoadState.Loading; // 投递数据 byte[] bodyRaw = Encoding.UTF8.GetBytes(PostContent); // 下载文件 CacheRequest = new UnityWebRequest(URL, UnityWebRequest.kHttpVerbPOST); UploadHandlerRaw uploadHandler = new UploadHandlerRaw(bodyRaw); DownloadHandlerBuffer downloadhandler = new DownloadHandlerBuffer(); CacheRequest.uploadHandler = uploadHandler; CacheRequest.downloadHandler = downloadhandler; CacheRequest.disposeDownloadHandlerOnDispose = true; CacheRequest.timeout = ResDefine.WebRequestTimeout; yield return(CacheRequest.SendWebRequest()); // Check error if (CacheRequest.isNetworkError || CacheRequest.isHttpError) { LogSystem.Log(ELogType.Warning, $"Failed to request web post : {URL} Error : {CacheRequest.error}"); LoadState = EWebLoadState.LoadFailed; } else { LoadState = EWebLoadState.LoadSucceed; } // Invoke callback LoadCallback?.Invoke(this); }
public void LoadFromFileAndHide() { string deckText = string.Empty; try { deckText = File.ReadAllText(DeckFiles[SelectedFileName]); } catch (Exception e) { Debug.LogError(DeckLoadErrorMessage + e.Message); } Deck newDeck = Deck.Parse(CardGameManager.Current, SelectedFileName, CardGameManager.Current.DeckFileType, deckText); LoadCallback?.Invoke(newDeck); ResetCancelButton(); Hide(); }
public static void LoadFullTweet(long id, LoadCallback callback) { TwitterAccount.CurrentAccount.Download ("http://api.twitter.com/1/statuses/show.json?id="+id, result => { if (result == null) callback (null); var tweet = Tweet.ParseTweet (new MemoryStream (result)); if (tweet == null) callback (null); callback (tweet); }); }