/// <summary> /// Refreshes the current skin, useful when the provided skin needs to change. /// </summary> /// <param name="skipFlash">a <c>bool</c> that determines if the knight should flash white</param> public static void RefreshSkin(bool skipFlash) { CoroutineHelper.GetRunner().StartCoroutine(ChangeSkinRoutine(skipFlash)); }
public static void UnloadSceneOverTime(string sceneName, Action onLoaded = null) { CoroutineHelper.Start(UnloadAdditive(sceneName, onLoaded)); }
/// <summary> /// 按照float进行Tween动画 /// </summary> /// <param name="tweenClip"></param> public static void DoTweenFloat(floatTweenClip tweenClip) { CoroutineHelper.StaticStartCoroutine(DoClip(tweenClip)); }
internal static void Load() { CoroutineHelper.GetRunner().StartCoroutine(Start()); }
public static void StartServices() { Time.DoStart(); CoroutineHelper.DoStart(); }
private IEnumerator _LoadAssetBundleAsync(AssetBundleInfo bundleInfo, bool loadDependence = true) { while (bundleInfo.isLoading) { yield return(null); } if (bundleInfo.isDone) { yield break; } Debug.LogFormat("AssetBundleManager._LoadAssetBundleAsync {0}", bundleInfo.url); bundleInfo.isLoading = true; if (loadDependence) { yield return(CoroutineHelper.Run(_LoadDependenciesAsync(bundleInfo.pack))); } string bundleName = bundleInfo.pack.name; string bundleNameV = bundleName;// + "." + bundleInfo.pack.checksum; string loadpath = null; #if !USE_BUNDLE_IN_EDITOR && (UNITY_EDITOR || UNITY_STANDALONE || !PUBLISH || ENABLE_GM) string search_path = System.IO.Path.Combine(Application.persistentDataPath, bundleNameV); string search_path2 = System.IO.Path.Combine(Defines.LuaFileSearchPath[2], bundleNameV); if (System.IO.File.Exists(search_path)) { loadpath = search_path; Debug.LogFormat("AssetBundleManager._LoadAssetBundleAsync search_path {0}", search_path); } else if (System.IO.File.Exists(search_path2)) { loadpath = search_path2; Debug.LogFormat("AssetBundleManager._LoadAssetBundleAsync search_path {0}", search_path); } #endif if (loadpath == null) { loadpath = bundleInfo.url; } AssetBundleCreateRequest loader = AssetBundle.LoadFromFileAsync(loadpath); yield return(loader); if (bundleInfo.isDone) // loaded by sync method { if (loader.isDone && loader.assetBundle != null) { loader.assetBundle.Unload(false); } yield break; } if (!loader.isDone) { bundleInfo.isLoading = false; Debug.LogErrorFormat("AssetBundleManager.LoadAssetBundleAsync can't async load bundle: {0} reason: {1}", bundleName, "NOT FOUND!"); } else { bundleInfo.isLoading = false; if (loader.assetBundle != null) { bundleInfo.bundle = loader.assetBundle; bundleInfo.isDone = true; Debug.LogFormat("AssetBundleManager.LoadAssetBundleAsync async load done bundle: {0}", bundleName); } else { Debug.LogErrorFormat("AssetBundleManager.LoadAssetBundleAsync can't async load bundle: {0}", bundleName); } } }
public Coroutine LoadBundleAsync(string name, System.Action <Object> callback) { return(CoroutineHelper.Run(_DoLoadBundleAsync(name, callback))); }
/// <summary> /// 用该函数代替OnEnable(因为OnEnable会在gameObject.SetActive(xxx);时被调用(导致错乱) /// </summary> public void Init() { CoroutineHelper.Run(Coroutine_Delay()); }
public void Interpret(EntityInfo entityInfo) { if (entityInfo.Name == "StartPosition" && GameData.Get("Player/Position") == null) { GameGlobal.Player.Position = new Vector2(entityInfo.Position.X * 16, entityInfo.Position.Y * 16); } else if (entityInfo.Name == "Switch") { new Entity(entity => { entity.AddComponent(new Switch(entityInfo)); }); } else if (entityInfo.Name == "MovableObject") { ZInterpreter data = new ZInterpreter(entityInfo.Data); new Entity(entity => { entity.LayerName = "Main"; entity.SortingLayer = GameGlobal.PlayerGraphicEntity.SortingLayer - 1; entity.Position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; entity.AddComponent(new Sprite()).Run <Sprite>(sprite => { sprite.LoadTexture("Graphics/WoodenBox"); }); entity.AddComponent(new MoveableObject()); if (data.GetString("id") != null) { entity.Data.Add("PO_ID", data.GetString("id")); string poidposstr = GameData.Get("PO_ID:" + entity.Data["PO_ID"] + "/Position"); if (poidposstr != null) { string[] poidpos = poidposstr.Split(','); entity.Position = new Vector2((float)Convert.ToDouble(poidpos[0]), (int)Convert.ToDouble(poidpos[1])); } } }); } else if (entityInfo.Name == "MovablePlatform") { ZInterpreter data = new ZInterpreter(entityInfo.Data); new Entity(entity => { entity.LayerName = "Main"; entity.SortingLayer = 10; entity.Position = entityInfo.Position * 16; entity.AddComponent(new Sprite()).Run <Sprite>(sprite => { sprite.BuildRectangle(new Point(32, 16), Color.White); }); entity.AddComponent(new MovablePlatform(entity.Position)).Run <MovablePlatform>(mp => { mp.Speed = (data.HasKey("speed")) ? data.GetFloat("speed") : 1; mp.XDistance = (data.HasKey("xdistance")) ? data.GetFloat("xdistance") : 0; mp.YDistance = (data.HasKey("ydistance")) ? data.GetFloat("ydistance") : 0; }); }); } else if (entityInfo.Name == "LightSource") { ZInterpreter data = new ZInterpreter(entityInfo.Data); // Pre set light sources if (data.HasKey("type")) { if (data.GetString("type") == "OrangeTorch") { Level.RenderBlender.DrawableTextures.Add(new RenderBlender.DrawableTexture("alphamask2") { Position = (entityInfo.Position * 16), Blend = RenderBlender.Subtract, Update = item => { item.Scale = 1.6f; } }); Level.RenderBlender.DrawableTextures.Add(new RenderBlender.DrawableTexture("alphamask2") { Position = (entityInfo.Position * 16), Color = Color.Orange * 0.1f, Update = item => { item.Scale = 0.6f + 0.04f * (float)Math.Sin(GameGlobal.TimeLoop * 50); } }); } else if (data.GetString("type") == "BlueMushroom") { Level.RenderBlender.DrawableTextures.Add(new RenderBlender.DrawableTexture("alphamask2") { Position = (entityInfo.Position * 16), Blend = RenderBlender.Subtract, Color = Color.White * 0.8f, Update = item => { item.Scale = 1.3f; } }); Level.RenderBlender.DrawableTextures.Add(new RenderBlender.DrawableTexture("alphamask") { Position = (entityInfo.Position * 16), Color = Color.DeepSkyBlue * 0.2f, Update = item => { item.Scale = 0.6f + 0.03f * (float)Math.Sin(GameGlobal.TimeLoop * 3); } }); } } // Custom light sources else { Level.RenderBlender.DrawableTextures.Add(new RenderBlender.DrawableTexture(data.GetString("texture") != "" ? data.GetString("texture"): "White") { Position = (entityInfo.Position * 16) + data.GetPointArr("offset")[0].ToVector2(), Blend = (data.GetString("blendstate") == "Subtract") ? RenderBlender.Subtract : RenderBlender.Lighting, Color = GameMethods.GetProperty <Color>(data.GetString("color")), Scale = data.GetFloat("scale"), Layer = data.GetInt("layer") }); } } else if (entityInfo.Name == "Lighting") { ZInterpreter data = new ZInterpreter(entityInfo.Data); Level.RenderBlender.ClearColor = Color.Black * data.GetFloat("darkness"); } else if (entityInfo.Name == "SavePoint") { new SavePoint(entityInfo); } else if (entityInfo.Name == "Enemy") { ZInterpreter data = new ZInterpreter(entityInfo.Data); Type type = Type.GetType("MyGame.Enemies." + data.GetString("type")); Activator.CreateInstance(type, new object[] { entityInfo }); } else if (entityInfo.Name == "Audio2D") { ZInterpreter data = new ZInterpreter(entityInfo.Data); Vector2 position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; float distance = ((data.HasKey("distance")) ? data.GetFloat("distance") : 5) * 16; float minvolume = ((data.HasKey("minvolume")) ? data.GetFloat("minvolume") : 0); float maxvolume = ((data.HasKey("maxvolume")) ? data.GetFloat("maxvolume") : 1); SoundEffectInstance sfi = Global.AudioController.Play("SFX/" + data.GetString("file")); sfi.Volume = 0; CoroutineHelper.Always(() => { if (Global.RunWhenEventLoops("ReplaySFX_" + data.GetString("file"), sfi == null || sfi.State != SoundState.Playing)) { sfi = Global.AudioController.Play("SFX/" + data.GetString("file")); } float difference = GameGlobal.Player.Position.GetDistance(position); float percent = (((difference - distance) * 100) / ((maxvolume) - distance)).Between(minvolume, maxvolume); sfi.Volume = (percent / 100); }); Global.SceneManager.CurrentScene.OnExit += () => { Global.AudioController.Stop("SFX/" + data.GetString("file")); }; } else if (entityInfo.Name == "InteractScript") { ZInterpreter data = new ZInterpreter(entityInfo.Data); new Entity(entity => { entity.Name = "InteractScript"; entity.LayerName = "Main"; entity.Data.Add("Script", data.GetString("script")); entity.SortingLayer = GameGlobal.Player.SortingLayer; entity.Position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; entity.AddComponent(new Drawable()).Run <Drawable>(d => { d.BuildRectangle(new Point(entityInfo.Size.X * 16, entityInfo.Size.Y * 16), Color.Blue); d.Visible = false; }); entity.AddComponent(new Collider()).Run <Collider>(c => { c.TriggerType = Collider.TriggerTypes.NonSolid; c.ColliderType = Collider.ColliderTypes.Box; }); if (data.HasKey("autoscript")) { CoroutineHelper.WaitRun(0.1f, () => { string[] script = data.GetString("autoscript").Split('.'); Type type = Type.GetType("MyGame." + script[0]); MethodInfo mi = type.GetMethod(script[1], BindingFlags.Static | BindingFlags.Public); mi.Invoke(null, new object[] { entity }); }); } }); } else if (entityInfo.Name == "TouchScript") { ZInterpreter data = new ZInterpreter(entityInfo.Data); new Entity(entity => { entity.Name = "TouchScript"; entity.LayerName = "Main"; entity.Data.Add("Script", data.GetString("script")); entity.SortingLayer = GameGlobal.Player.SortingLayer; entity.Position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; entity.AddComponent(new Drawable()).Run <Drawable>(d => { d.BuildRectangle(new Point(entityInfo.Size.X * 16, entityInfo.Size.Y * 16), Color.Blue); d.Visible = false; }); entity.AddComponent(new Collider()).Run <Collider>(c => { c.TriggerType = Collider.TriggerTypes.NonSolid; c.ColliderType = Collider.ColliderTypes.Box; }); }); } else if (entityInfo.Name == "Ambience") { ZInterpreter data = new ZInterpreter(entityInfo.Data); SoundEffectInstance sfi = Global.AudioController.Play("SFX/" + data.GetString("file")); sfi.Volume = (data.HasKey("volume")) ? data.GetFloat("volume") : 1; CoroutineHelper.Always(() => { if (sfi.State == SoundState.Stopped) { sfi = Global.AudioController.Play("SFX/" + data.GetString("file")); sfi.Volume = (data.HasKey("volume")) ? data.GetFloat("volume") : 1; } }); Global.SceneManager.CurrentScene.OnExit += () => { Global.AudioController.Stop("SFX/" + data.GetString("file")); }; } else if (entityInfo.Name == "Music") { ZInterpreter data = new ZInterpreter(entityInfo.Data); float fadeTo = (data.HasKey("fadeTo")) ? data.GetFloat("fadeTo") : 1; if (Global.AudioController.CurrentMusicFile == null || Global.AudioController.CurrentMusicFile == "") { Global.AudioController.PlayMusic(data.GetString("file")); Global.AudioController.CurrentMusicVolume = fadeTo; } else { Global.AudioController.PlayMusic(data.GetString("file"), fadeTo); } } else if (entityInfo.Name == "NPCChest") { ZInterpreter data = new ZInterpreter(entityInfo.Data); NPCChest.Create(entityInfo, data); } else if (entityInfo.Name == "Chest") { ZInterpreter data = new ZInterpreter(entityInfo.Data); new Entity(entity => { entity.Name = "Chest"; entity.LayerName = "Main"; entity.SortingLayer = GameGlobal.Player.SortingLayer - 1; entity.Position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; entity.AddComponent(new Sprite()).Run <Sprite>(d => { d.LoadTexture("Entities/Chest_" + data.GetString("type")); d.AddAnimation(new Animation("Closed", 0, new Point(32, 32), new Point(0, 0))); d.AddAnimation(new Animation("Opening", 0.1f, new Point(32, 32), new Point(1, 0), new Point(2, 0), new Point(3, 0), new Point(4, 0))); d.RunAnimation("Closed"); }); entity.AddComponent(new Collider()).Run <Collider>(c => { c.TriggerType = Collider.TriggerTypes.NonSolid; c.ColliderType = Collider.ColliderTypes.Box; }); }); } else if (entityInfo.Name == "NPC") { ZInterpreter data = new ZInterpreter(entityInfo.Data); new Entity(entity => { entity.Name = "NPC"; entity.LayerName = "Main"; entity.SortingLayer = GameGlobal.Player.SortingLayer; entity.Position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; entity.Origin = Vector2.Zero; entity.AddComponent(new Drawable()).Run <Drawable>(d => { d.BuildRectangle(new Point(entityInfo.Size.X * 16, entityInfo.Size.Y * 16), Color.CornflowerBlue); }); entity.AddComponent(new Collider()).Run <Collider>(c => { c.TriggerType = Collider.TriggerTypes.NonSolid; c.ColliderType = Collider.ColliderTypes.Box; }); }); } else if (entityInfo.Name == "Water") { ZInterpreter data = new ZInterpreter(entityInfo.Data); new Entity(entity => { entity.Name = "Water"; entity.LayerName = "Main"; entity.SortingLayer = 4; entity.Opacity = 1f; entity.Position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; entity.AddComponent(new Drawable()).Run <Drawable>(d => { Color waterColor = (data.HasKey("color")) ? GameMethods.GetProperty <Color>(data.GetString("color")) * 0.2f : new Color(0, 0, 0, 0.2f); d.BuildRectangle(new Point(entityInfo.Size.X * 16, entityInfo.Size.Y * 16), waterColor); /* Animate water */ int offset = 0; Color[] colors = new Color[6]; for (int i = 0; i < colors.Length; i++) { colors[i] = (i % 6 >= 3) ? Color.AliceBlue * 0.3f : Color.DarkSlateBlue * 0.1f; } colors[3] = Color.AliceBlue * 0.5f; int offsetPrev = 0; CoroutineHelper.Always(() => { offset = 6 + (int)(Math.Sin(Global.GameTime.TotalGameTime.TotalMilliseconds / 500) * 3); if (offset != offsetPrev) { offsetPrev = offset; d.Texture2D.ManipulateColorsRect1D(new Rectangle(0, 0, d.Texture2D.Width, 2), colors1D => { int width = d.Texture2D.Width; for (int x = 0; x < width; x++) { colors1D[0 * width + x] = colors[(x + offset).Wrap(0, colors.Length - 1)]; colors1D[1 * width + x] = colors[(2 - x + offset / 2).Wrap(0, colors.Length - 1)] * 0.5f; } return(colors1D); }); } }); /* /Animate water */ }); entity.AddComponent(new Collider()).Run <Collider>(c => { c.TriggerType = Collider.TriggerTypes.NonSolid; c.ColliderType = Collider.ColliderTypes.Box; }); }); } else if (entityInfo.Name == "Background") { ZInterpreter data = new ZInterpreter(entityInfo.Data); new Entity(entity => { entity.LayerName = "Background"; entity.Position = new Vector2(0, 0); if (data.HasKey("sortinglayer")) { entity.SortingLayer = data.GetInt("sortinglayer"); } if (data.HasKey("opacity")) { entity.Opacity = data.GetFloat("opacity"); } float[] coefficient = data.GetFloatArr("coefficient"); float[] offset = data.GetFloatArr("offset"); entity.AddComponent(new CameraOffsetTexture() { Texture2D = Global.Content.Load <Texture2D>("Backgrounds/" + data.GetString("image")), Coefficient = new Vector2(coefficient[0], coefficient[1]), Offset = new Vector2(offset[0], offset[1]) }); if (data.HasKey("animate")) { entity.GetComponent <CameraOffsetTexture>().Animate = true; entity.GetComponent <CameraOffsetTexture>().AnimStepTime = data.GetFloat("animate"); entity.GetComponent <CameraOffsetTexture>().Size = data.GetPointArr("crop")[0]; } }); } else if (entityInfo.Name == "Foreground") { ZInterpreter data = new ZInterpreter(entityInfo.Data); new Entity(entity => { entity.LayerName = "Foreground"; entity.Position = Vector2.Zero; entity.SortingLayer = 8; float[] coefficient = data.GetFloatArr("coefficient"); float[] offset = data.GetFloatArr("offset"); entity.AddComponent(new CameraOffsetTexture() { Texture2D = Global.Content.Load <Texture2D>("Foregrounds/" + data.GetString("image")), Coefficient = new Vector2(coefficient[0], coefficient[1]), Offset = new Vector2(offset[0], offset[1]) }); if (data.HasKey("animate")) { entity.GetComponent <CameraOffsetTexture>().Animate = true; entity.GetComponent <CameraOffsetTexture>().AnimStepTime = data.GetFloat("animate"); entity.GetComponent <CameraOffsetTexture>().Size = data.GetPointArr("crop")[0]; } }); } else if (entityInfo.Name == "AutoDoor") { new Entity(entity => { entity.Name = "AutoDoor"; entity.LayerName = "Main"; ZInterpreter data = new ZInterpreter(entityInfo.Data); entity.Data.Add("Level", data.GetString("level")); entity.Data.Add("Position", data.GetString("position")); entity.SortingLayer = GameGlobal.Player.SortingLayer + 5; entity.Position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; entity.AddComponent(new Drawable()).Run <Drawable>(d => { d.BuildRectangle(new Point(entityInfo.Size.X * 16, entityInfo.Size.Y * 16), Color.Blue); d.Visible = false; }); entity.AddComponent(new Collider()).Run <Collider>(c => { c.TriggerType = Collider.TriggerTypes.NonSolid; c.ColliderType = Collider.ColliderTypes.Box; }); }); } else if (entityInfo.Name == "Door") { new Entity(entity => { entity.Name = "Door"; entity.LayerName = "Main"; ZInterpreter data = new ZInterpreter(entityInfo.Data); entity.Data.Add("Level", data.GetString("level")); entity.Data.Add("Position", data.GetString("position")); entity.SortingLayer = GameGlobal.Player.SortingLayer; entity.Position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; entity.AddComponent(new Drawable()).Run <Drawable>(d => { d.BuildRectangle(new Point(entityInfo.Size.X * 16, entityInfo.Size.Y * 16), Color.Blue); d.Visible = false; }); entity.AddComponent(new Collider()).Run <Collider>(c => { c.TriggerType = Collider.TriggerTypes.NonSolid; c.ColliderType = Collider.ColliderTypes.Box; }); }); } else if (entityInfo.Name == "Graphic") { ZInterpreter data = new ZInterpreter(entityInfo.Data); new Entity(entity => { entity.Name = "Graphic"; entity.LayerName = "Main"; entity.SortingLayer = (data.HasKey("sortinglayer")) ? data.GetInt("sortinglayer") : 2; entity.Position = (entityInfo.Position * 16); if (data.HasKey("origin")) { var origin = data.GetFloatArr("origin"); entity.Origin = new Vector2(origin[0], origin[1]); if (entity.Origin.X == 1) { entity.Position.X += (16 * entity.Origin.X); } if (entity.Origin.Y == 1) { entity.Position.Y += (16 * entity.Origin.Y); } } if (data.HasKey("collider")) { entity.AddComponent(new Collider()); if (data.GetString("collider").ToLower() == "pixel") { entity.GetComponent <Collider>().ColliderType = Collider.ColliderTypes.Pixel; } else if (data.GetString("collider").ToLower() == "box") { if (data.HasKey("boxrect")) { int[] boxrect = data.GetIntArr("boxrect"); entity.GetComponent <Collider>().ColliderType = Collider.ColliderTypes.Box; entity.GetComponent <Collider>().Offset = new Offset(boxrect[0], boxrect[1], boxrect[2], boxrect[3]); } } } if (data.HasKey("offset")) { var offset = data.GetFloatArr("offset"); entity.Position += new Vector2(offset[0], offset[1]); } if (data.HasKey("id")) { entity.ID = data.GetString("id"); } entity.AddComponent(new Sprite()).Run <Sprite>(d => { d.LoadTexture("Graphics/" + data.GetString("image")); }); }); } else if (entityInfo.Name == "Animation") { new Entity(entity => { entity.Name = "Animation"; entity.LayerName = "Main"; entity.Origin = Vector2.Zero; entity.SortingLayer = 2; ZInterpreter data = new ZInterpreter(entityInfo.Data); entity.Opacity = (data.HasKey("opacity")) ? data.GetFloat("opacity") : 1; entity.AddComponent(new Sprite()).Run <Sprite>(d => { d.LoadTexture("Graphics/" + data.GetString("image")); d.AddAnimation(new Animation("Default", data.GetFloat("delay"), data.GetPointArr("size")[0], data.GetPointArr("frames"))); d.RunAnimation("Default"); entity.Position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; }); }); } else if (entityInfo.Name == "CameraLock") { new Entity(entity => { entity.Name = "CameraLock"; entity.LayerName = "Main"; entity.Data.Add("Type", entityInfo.Data); entity.SortingLayer = GameGlobal.Player.SortingLayer; entity.Opacity = 0; entity.AddComponent(new Drawable()).Run <Drawable>(d => { d.BuildRectangle(new Point(entityInfo.Size.X * 16, entityInfo.Size.Y * 16), Color.Red); entity.Position = (entityInfo.Position * 16) + (entityInfo.Size.ToVector2() / 2) * 16; }); entity.AddComponent(new Collider()).Run <Collider>(c => { c.TriggerType = Collider.TriggerTypes.NonSolid; c.ColliderType = Collider.ColliderTypes.Box; }); }); } }
public void ShowScene(string scene_name, Action call_back = null, bool release_scene = false) { CoroutineHelper.Start(_LoadingScene(scene_name, call_back, release_scene)); }
public void LoadScene(string sceneName, float delay) { CoroutineHelper.NewCoroutine(DelayLoadScene(sceneName, delay)); }
private static void UpdateServices() { Lockstep.Util.LTime.DoUpdate(); CoroutineHelper.DoUpdate(); }
private static void StartServices() { Lockstep.Util.LTime.DoStart(); CoroutineHelper.DoStart(); }
public static void InitialiseAssets() { CoroutineHelper.Always(() => { TimeLoop = (TimeLoop + Global.DeltaTime).Between(0, (float)Math.PI * 360); }); // Fader Fader = new Entity(entity => { entity.LayerName = "Fade"; entity.Data.Add("Time", ""); entity.Data.Add("Cancel", ""); entity.AddComponent(new Drawable()).Run <Drawable>(component => { component.BuildRectangle(new Point(Global.ScreenBounds.Width, Global.ScreenBounds.Height), Color.Black); }); entity.AddFunction("SetDefault", (e) => { entity.Data["Time"] = "0.5"; entity.Data["Cancel"] = "false"; }); entity.RunFunction("SetDefault"); entity.AddFunction("FadeIn", (e, c) => { entity.RunFunction("BlackOut"); CoroutineHelper.RunFor((float)Convert.ToDecimal(entity.Data["Time"]), pcnt => { if (entity.Data["Cancel"] != "true") { e.Opacity = 1 - pcnt; } }, () => { c?.Invoke(e); }); }); entity.AddFunction("FadeOut", (e, c) => { entity.RunFunction("InstantIn"); CoroutineHelper.RunFor((float)Convert.ToDecimal(entity.Data["Time"]), pcnt => { if (entity.Data["Cancel"] != "true") { e.Opacity = pcnt; } }, () => { c?.Invoke(e); }); }); entity.AddFunction("InstantIn", (e) => { e.Opacity = 0; }); entity.AddFunction("BlackOut", (e) => { e.Opacity = 1; }); entity.AddFunction("Cancel", (e) => { entity.Data["Cancel"] = "true"; }); entity.AddFunction("Resume", (e) => { entity.Data["Cancel"] = "false"; }); }); }
public static Coroutine LoadSceneAsync(string name, System.Action <bool> callback) { AssetBundleManager.Instance.ReleaseSceneCachedBundleOnSceneSwitch(); return(CoroutineHelper.Run(_DoLoadSceneAsync(name, callback))); }
private IEnumerator DetectSoundFinished(float delaySound) { if (useIntroSilence && introSilenceMax > 0f) { var rndSilence = UnityEngine.Random.Range(introSilenceMin, introSilenceMax); isWaitingForDelay = true; yield return(StartCoroutine(CoroutineHelper.WaitForRealSeconds(rndSilence))); isWaitingForDelay = false; } if (delaySound > 0f) { isWaitingForDelay = true; yield return(StartCoroutine(CoroutineHelper.WaitForRealSeconds(delaySound))); isWaitingForDelay = false; } if (curDetectEndMode != DetectEndMode.DetectEnd) { yield break; } _audio.Play(); lastTimePlayed = Time.time; // sound play worked! Duck music if a ducking sound. MasterAudio.DuckSoundGroup(ParentGroup.name, _audio); var clipLength = Math.Abs(_audio.clip.length / _audio.pitch); yield return(StartCoroutine(CoroutineHelper.WaitForRealSeconds(clipLength))); // wait for clip to play if (HasActiveFXFilter && fxTailTime > 0f) { yield return(StartCoroutine(CoroutineHelper.WaitForRealSeconds(fxTailTime))); } var playSnd = playSndParams; if (curDetectEndMode != DetectEndMode.DetectEnd) { yield break; } if (!_audio.loop || (playSndParams != null && playSndParams.isChainLoop)) { Stop(); } if (playSnd != null && playSnd.isChainLoop) { // check if loop count is over. if (ParentGroup.chainLoopMode == MasterAudioGroup.ChainedLoopLoopMode.NumberOfLoops && ParentGroup.ChainLoopCount >= ParentGroup.chainLoopNumLoops) { // done looping yield break; } var rndDelay = playSnd.delaySoundTime; if (ParentGroup.chainLoopDelayMin > 0f || ParentGroup.chainLoopDelayMax > 0f) { rndDelay = UnityEngine.Random.Range(ParentGroup.chainLoopDelayMin, ParentGroup.chainLoopDelayMax); } // cannot use "AndForget" methods! Chain loop needs to check the status. if (playSnd.attachToSource || playSnd.sourceTrans != null) { if (playSnd.attachToSource) { MasterAudio.PlaySound3DFollowTransform(playSnd.soundType, playSnd.sourceTrans, playSnd.volumePercentage, playSnd.pitch, rndDelay, null, true); } else { MasterAudio.PlaySound3DAtTransform(playSnd.soundType, playSnd.sourceTrans, playSnd.volumePercentage, playSnd.pitch, rndDelay, null, true); } } else { MasterAudio.PlaySound(playSnd.soundType, playSnd.volumePercentage, playSnd.pitch, rndDelay, null, true); } } }
private static Coroutine _StartCoroutine(IEnumerator em) { return(CoroutineHelper.Run(em)); }
//--------------------------------------------------------------------------------------------- // Unity Overrides //--------------------------------------------------------------------------------------------- private void Awake() { instance = this; DontDestroyOnLoad(this); }
public Coroutine LoadAssetAsync(XManifest.AssetInfo info, System.Type type, System.Action <Object> callback) { return(CoroutineHelper.Run(_DoLoadAssetAsync(info, type, callback))); }
void OnEnable() { mCoroutine = CoroutineHelper.StartCoroutine(A()); }
public Coroutine LoadScene(XManifest.Scene info) { return(CoroutineHelper.Run(_DoLoadScene(info))); }
void OnDisable() { CoroutineHelper.StopCoroutine(mCoroutine); }
// Triggers end game visuals void EndGameVisualsInternal(int?randomSeed = null) { Random.State oldState = Random.state; System.Guid seededGuid = System.Guid.NewGuid(); // If we're seeding this EndGameVisuals, it means it will be exactly the same across both players. We need to make sure to reset the old state however if (randomSeed != null) { Random.InitState((int)randomSeed); oldState = Random.state; // Generate a seeded GUID, which will be the same if we use the same seed across players var guidBytes = new byte[16]; new System.Random((int)randomSeed).NextBytes(guidBytes); seededGuid = new System.Guid(guidBytes); } int visualType = Random.Range(1, 8); // Time before ending the visuals routine float visualsDuration = 0.0f; // Counters, used for delaying visuals int counter = 0; int reverseCounter = placedVisualsFlat.Count(x => x != null); int count = reverseCounter; // Some fixed random values float fixedFloat = Random.value; // <- Always positive Vector3 fixedVector = Random.insideUnitSphere; // <- XYZ can be negative or positive // The center of the board Vector3 center = (Vector3.up * (ConnectFour.BOARD_HEIGHT / 2.0f)) * boardScale; center += Vector3.forward * (fixedFloat > 0.33f ? fixedFloat > 0.66f ? 0.5f : -0.5f : 0.0f); // Set the gravity, and save the old one Vector3 gravityPrev = Physics.gravity; Physics.gravity = Vector3.up * gravityScale; // Determines whether to shuffle the balls or not bool shuffleBalls = Random.value > 0.5f; Debug.LogFormat("ConnectFourBoard : EndGameVisuals - visualType = {0}, randomSeed = {1}, shuffleBalls = {2}, fixedFloat = {3}, fixedVector = {4}, seededGuid = {5}", visualType, randomSeed, shuffleBalls, fixedFloat, fixedVector, seededGuid); var balls = shuffleBalls ? placedVisualsFlat.OrderBy(x => seededGuid) : placedVisualsFlat; foreach (var obj in balls) { if (obj == null) { continue; } switch (visualType) { // Shoot up, with gravity, with collision case 1: { var rb = obj.AddComponent <Rigidbody>(); var coll = obj.AddComponent <SphereCollider>(); rb.isKinematic = false; rb.useGravity = true; // Add a very small amount of downward force rb.AddForce(Vector3.up * (explosionForce + obj.transform.position.y), ForceMode.Impulse); visualsDuration = 5.0f; break; } // Fall with gravity, with collision, all at once case 2: { var rb = obj.AddComponent <Rigidbody>(); var coll = obj.AddComponent <SphereCollider>(); rb.isKinematic = false; rb.useGravity = true; // 0 - Adding a random-strength, random-direction force on each if (fixedFloat < 0.25f) { rb.AddForce(Random.insideUnitSphere * Random.value, ForceMode.Impulse); } // 0.25 - Adding a fixed-strength, fixed direction force on each else if (fixedFloat < 0.5f) { rb.AddForce(fixedVector * fixedFloat, ForceMode.Impulse); } // 0.5 - Adding a fixed-strength, random-direction force on each else if (fixedFloat < 0.75f) { rb.AddForce(Random.insideUnitSphere * fixedFloat * 2.0f, ForceMode.Impulse); } // 0.75 - Adding a random-strength, fixed-direction force on each else if (fixedFloat <= 1.00f) { rb.AddForce(fixedVector * Random.value, ForceMode.Impulse); } visualsDuration = 5.0f; break; } // Fall with gravity, without collision, one by one. This starts in the top left and goes from top to bottom, left to right case 3: { var rb = obj.AddComponent <Rigidbody>(); rb.isKinematic = true; rb.useGravity = false; // Reverse the effect half the time int index = fixedFloat > 0.5f ? counter : reverseCounter; float delay = (0.15f * fixedFloat); CoroutineHelper.InvokeDelayed(index * delay, () => { rb.isKinematic = false; rb.useGravity = true; }); visualsDuration += delay + (0.5f / count); break; } // Tween the scale of the object using Ease.InBack, all at once case 4: { obj.transform.DOScale(0.0f, 0.5f).SetEase(Ease.InBack); visualsDuration = 1.0f + (0.5f / count); break; } // Tween the scale of the object using Ease.InBack, one by one case 5: { // Reverse the effect half the time int index = fixedFloat > 0.5f ? counter : reverseCounter; float delay = (0.15f * fixedFloat); obj.transform.DOScale(0.0f, 0.5f).SetEase(Ease.InBack).SetDelay(index * delay); // Add the delay to the visualsDuration visualsDuration += delay + (0.5f / count); break; } // Fade alpha out, one by one case 6: { var r = obj.GetComponent <Renderer>(); // Reverse the effect half the time int index = fixedFloat > 0.5f ? counter : reverseCounter; float delay = (0.15f * fixedFloat); r.material.DOFloat(0.0f, SHADER_ALPHA, 0.25f).SetDelay(index * delay) .OnComplete(() => r.gameObject.SetActive(false)); // Add the delay+duration to the visualsDuration visualsDuration += delay + (0.25f / count); break; } // Ramp brightness then fade brightness+alpha case 7: { // Reverse the effect half the time int index = fixedFloat > 0.5f ? counter : reverseCounter; float delay = (0.15f * fixedFloat); var r = obj.GetComponent <Renderer>(); r.material.DOFloat(3.0f, SHADER_BRIGHTNESS, 0.5f).SetDelay(index * delay); r.material.DOFloat(0.0f, SHADER_BRIGHTNESS, 1f).SetDelay((index * delay) + 0.5f); r.material.DOFloat(0.0f, SHADER_ALPHA, 1f).SetDelay((index * delay) + 0.5f) .OnComplete(() => r.gameObject.SetActive(false)); visualsDuration += delay + (1.5f / count); break; } default: { Debug.LogError("ConnectFourBoard : EndGameVisuals - Effect for visual type " + visualType + " doesn't exist!"); return; } } counter++; reverseCounter--; } // Reset random state if (randomSeed != null) { Random.state = oldState; } // Reset all the objects that were affected by the end game visuals. This occurs both after the delay before doing the visuals, plus the duration of the visuals themselves CoroutineHelper.InvokeDelayed(visualsDuration, () => { // Fade out every ball foreach (var obj in placedVisuals) { if (obj == null) { continue; } var r = obj.GetComponent <Renderer>(); if (r.material != null && r.material.GetFloat(SHADER_ALPHA) > 0.0f) { r.material.DOFloat(0.0f, SHADER_ALPHA, 0.5f) .OnComplete(() => r.gameObject.SetActive(false)); } } // Set the completedEndVisuals flag to true CoroutineHelper.InvokeDelayed(0.5f, () => completedEndVisuals = true); }); }
public void HandleNextBatch() { try { var kvps = _unstartedJobs.Take(Endpoint.MaxTranslationsPerRequest).ToList(); var untranslatedTexts = new List <string>(); var jobs = new List <TranslationJob>(); foreach (var kvp in kvps) { var key = kvp.Key; var job = kvp.Value; _unstartedJobs.Remove(key); Manager.UnstartedTranslations--; var unpreparedUntranslatedText = GetTextToTranslate(job); var untranslatedText = job.Key.PrepareUntranslatedText(unpreparedUntranslatedText); if (CanTranslate(unpreparedUntranslatedText)) { jobs.Add(job); untranslatedTexts.Add(untranslatedText); _ongoingJobs[key] = job; Manager.OngoingTranslations++; if (!Settings.EnableSilentMode) { XuaLogger.AutoTranslator.Debug("Started: '" + unpreparedUntranslatedText + "'"); } } else { XuaLogger.AutoTranslator.Warn($"Dequeued: '{unpreparedUntranslatedText}' because the current endpoint has already failed this translation 3 times."); job.State = TranslationJobState.Failed; job.ErrorMessage = "The endpoint failed to perform this translation 3 or more times."; Manager.InvokeJobFailed(job); } } if (jobs.Count > 0) { AvailableBatchOperations--; var jobsArray = jobs.ToArray(); CoroutineHelper.Start( Translate( untranslatedTexts.ToArray(), Settings.FromLanguage, Settings.Language, translatedText => OnBatchTranslationCompleted(jobsArray, translatedText), (msg, e) => OnTranslationFailed(jobsArray, msg, e))); } } finally { if (_unstartedJobs.Count == 0) { Manager.UnscheduleUnstartedJobs(this); } } }
public static void UpdateServices() { Time.DoUpdate(); CoroutineHelper.DoUpdate(); }
private void OnTranslationFailed(TranslationJob[] jobs, string error, Exception e) { if (e == null) { XuaLogger.AutoTranslator.Error(error); } else { XuaLogger.AutoTranslator.Error(e, error); } if (jobs.Length == 1) { foreach (var job in jobs) { var key = job.Key; job.State = TranslationJobState.Failed; job.ErrorMessage = error; RemoveOngoingTranslation(key); RegisterTranslationFailureFor(key.TemplatedOriginal_Text); Manager.InvokeJobFailed(job); XuaLogger.AutoTranslator.Error($"Failed: '{job.Key.TemplatedOriginal_Text}'"); } } else { if (!HasBatchLogicFailed) { CoroutineHelper.Start(EnableBatchingAfterDelay()); } HasBatchLogicFailed = true; for (int i = 0; i < jobs.Length; i++) { var job = jobs[i]; var key = job.Key; AddUnstartedJob(key, job); RemoveOngoingTranslation(key); XuaLogger.AutoTranslator.Error($"Failed: '{job.Key.TemplatedOriginal_Text}'"); } XuaLogger.AutoTranslator.Error("A batch operation failed. Disabling batching and restarting failed jobs."); } if (!HasFailedDueToConsecutiveErrors) { ConsecutiveErrors++; if (HasFailedDueToConsecutiveErrors) { XuaLogger.AutoTranslator.Error($"{Settings.MaxErrors} or more consecutive errors occurred. Shutting down translator endpoint."); ClearAllJobs(); } } }
protected override void ExecuteOverTime(float seconds) { CoroutineHelper.Start(Wait(seconds)); }
public void TheTree() { SoundEffectInstance forestAmbienceSFX = Global.AudioController.Play("SFX/Forest_Ambience"); forestAmbienceSFX.Volume = 0.3f; CoroutineHelper.Always(() => { if (forestAmbienceSFX.State == SoundState.Stopped) { forestAmbienceSFX = Global.AudioController.Play("SFX/Forest_Ambience"); forestAmbienceSFX.Volume = 0.3f; } }); Global.SceneManager.CurrentScene.OnExit += () => { Global.AudioController.Stop("SFX/Forest_Ambience"); }; if (GameData.Get("Levels/TheTree/Intro") == "True") { // Music Global.AudioController.PlayMusic("Overworld Happy"); return; } MyGame.Scenes.Level.CameraController.Offset = new Vector2(16, 0); // Initial fade GameGlobal.Fader.RunFunction("BlackOut"); GameGlobal.Fader.RunFunction("Cancel"); GameGlobal.Fader.Data["Time"] = "5"; CoroutineHelper.WaitRun(2, () => { GameGlobal.Fader.RunFunction("Resume"); GameGlobal.Fader.RunFunction("FadeIn"); }); GameGlobal.PlayerController.MovementEnabled = false; GameGlobal.PlayerController.Kinetic = true; GameGlobal.PlayerGraphic.Visible = false; GameGlobal.PlayerController.MovementMode = PlayerController.MovementModes.None; // Camera pan down Entity camePos = new Entity(e => { e.Position = GameGlobal.Player.Position + new Vector2(0, -800); }); CameraController.Instance.Easing = 0.03f; CameraController.Instance.MaxStep = 1f; CameraController.Instance.Target = camePos; CameraController.Instance.SnapOnce(); // Seagulls CoroutineHelper.WaitRun(11, () => { CoroutineHelper.WaitRun(1, () => { Global.AudioController.Play("SFX/BushRustle"); }); new Entity(entity => { entity.LayerName = "Main"; entity.SortingLayer = 8; entity.AddComponent(new Sprite() { Texture2D = Global.Content.Load <Texture2D>("Entities/Seagull") }).Run <Sprite>(s => { s.AddAnimation(new Animation("Default", 0.1f, new Point(16, 16), new Point(0, 0), new Point(1, 0), new Point(2, 0), new Point(3, 0), new Point(3, 0), new Point(3, 0))); s.RunAnimation("Default"); }); entity.Position = GameGlobal.Player.Position + new Vector2(0, -100); entity.Scale = new Vector2(2.1f, 2.1f); CoroutineHelper.RunUntil(() => { return(entity.Position.Y < -500); }, () => { entity.Position += new Vector2(0.3f, -0.2f * entity.Scale.Y); entity.Scale += new Vector2(-0.003f, -0.003f); if (entity.Scale.X < 0.5f) { entity.Scale = new Vector2(0.5f, 0.5f); } }); }); new Entity(entity => { entity.LayerName = "Main"; entity.SortingLayer = 8; entity.AddComponent(new Sprite() { Texture2D = Global.Content.Load <Texture2D>("Entities/Seagull") }).Run <Sprite>(s => { s.AddAnimation(new Animation("Default", 0.1f, new Point(16, 16), new Point(0, 0), new Point(1, 0), new Point(2, 0), new Point(3, 0), new Point(3, 0), new Point(3, 0))); s.RunAnimation("Default"); }); entity.Position = GameGlobal.Player.Position + new Vector2(-40, -100); entity.Scale = new Vector2(2, 2); CoroutineHelper.RunUntil(() => { return(entity.Position.Y < -500); }, () => { entity.Position += new Vector2(0.3f, -0.2f * entity.Scale.Y); entity.Scale += new Vector2(-0.003f, -0.003f); if (entity.Scale.X < 0.5f) { entity.Scale = new Vector2(0.5f, 0.5f); } }); }); }); CoroutineHelper.WaitRun(7, () => { camePos.Position = GameGlobal.Player.Position + new Vector2(0, -40); CoroutineHelper.WaitRun(12, () => { GameGlobal.Player.Position = camePos.Position + new Vector2(0, -20); GameGlobal.PlayerGraphic.RunAnimation("Jump"); GameMethods.ShowMessages(new List <MessageBox>() { new MessageBox("Pause", ".|.|.|| !", camePos.Position), new MessageBox("Pause", "Huh|.|.|.||| I don't remember\nsleeping there!?", camePos.Position) }, null, () => { CoroutineHelper.WaitRun(3, () => { GameGlobal.PlayerGraphic.Visible = true; MessageBox WoahMSG = new MessageBox("Pause", "Woah!", camePos.Position, MessageBox.Type.ManualDestroy); WoahMSG.Build(); float temp = GameGlobal.Player.Position.Y; CoroutineHelper.RunFor(0.7f, p => { if (GameGlobal.Player.Position.Y < camePos.Position.Y + 45) { GameGlobal.Player.Position.Y += 1f * (p * 4.15f); } if (GameGlobal.Player.Position.Y > WoahMSG.Position.Y + 32) { WoahMSG.Position = GameGlobal.Player.Position + new Vector2(-WoahMSG.Container.Size.X / 2, -32); } }, () => { GameGlobal.Player.Position.Y = camePos.Position.Y + 45; GameGlobal.PlayerGraphic.RunAnimation("Lay"); Global.AudioController.Play("SFX/Thump"); WoahMSG.Destroy(); GameMethods.SmokePuffs(8, GameGlobal.PlayerGraphicEntity.Position, new Point(8, 8)); CameraController.Instance.Shake(0.7f); CoroutineHelper.WaitRun(2, () => { // Music Global.AudioController.PlayMusic("Overworld Happy", 1); GameMethods.ShowMessages(new List <MessageBox>() { new MessageBox("Pause", "OUCH!", GameGlobal.Player.Position + new Vector2(0, -32)), }, null, () => { GameGlobal.PlayerController.MovementEnabled = true; GameGlobal.PlayerController.MovementMode = PlayerController.MovementModes.Normal; GameGlobal.PlayerController.Kinetic = false; CameraController.Instance.Easing = 0.1f; CameraController.Instance.MaxStep = 1000; CameraController.Instance.Target = GameGlobal.Player; camePos.Destroy(); GameGlobal.PlayerGraphic.RunAnimation("Stand"); GameGlobal.PlayerController.Direction = 1; GameGlobal.PlayerController.IsGrounded = true; GameData.Set("Levels/TheTree/Intro", "True"); GameGlobal.Fader.RunFunction("SetDefault"); }); }); }); }); }); }); }); }
/// <summary> /// Not implemt /// </summary> /// <typeparam name="T"></typeparam> /// <param name="tweenClip"></param> /// <param name="sumable"></param> public static void DoTween <T>(ITweenClip <T> tweenClip, ISumable <T> sumable) { CoroutineHelper.StaticStartCoroutine(DoClip(tweenClip, sumable)); }
private IEnumerator FadeInOut() { var fadeOutStartTime = VarAudio.clip.length - (fadeOutTime * VarAudio.pitch); // wait for clip to start playing if (MasterAudio.IgnoreTimeScale) { yield return(StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL))); } else { yield return(MasterAudio.InnerLoopDelay); } var stepVolumeUp = fadeMaxVolume / fadeInTime * MasterAudio.INNER_LOOP_CHECK_INTERVAL; curFadeMode = FadeMode.FadeInOut; // wait to set this so it stops the previous one if it's still going. if (fadeInTime > 0f) { while (VarAudio.isPlaying && curFadeMode == FadeMode.FadeInOut && VarAudio.time < fadeInTime) { VarAudio.volume += stepVolumeUp; if (MasterAudio.IgnoreTimeScale) { yield return(StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL))); } else { yield return(MasterAudio.InnerLoopDelay); } } } if (curFadeMode != FadeMode.FadeInOut) { yield break; // in case another fade cancelled this one } VarAudio.volume = fadeMaxVolume; // just in case it didn't align exactly if (fadeOutTime == 0f || VarAudio.loop) { yield break; // nothing more to do! } // wait for fade out time. while (VarAudio.isPlaying && curFadeMode == FadeMode.FadeInOut && VarAudio.time < fadeOutStartTime) { if (MasterAudio.IgnoreTimeScale) { yield return(StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL))); } else { yield return(MasterAudio.InnerLoopDelay); } } if (curFadeMode != FadeMode.FadeInOut) { yield break; // in case another fade cancelled this one } var stepVolumeDown = fadeMaxVolume / fadeOutTime * MasterAudio.INNER_LOOP_CHECK_INTERVAL; while (VarAudio.isPlaying && curFadeMode == FadeMode.FadeInOut && VarAudio.volume > 0) { VarAudio.volume -= stepVolumeDown; if (MasterAudio.IgnoreTimeScale) { yield return(StartCoroutine(CoroutineHelper.WaitForActualSeconds(MasterAudio.INNER_LOOP_CHECK_INTERVAL))); } else { yield return(MasterAudio.InnerLoopDelay); } } audio.volume = 0f; Stop(); if (curFadeMode != FadeMode.FadeInOut) { yield break; // in case another fade cancelled this one } curFadeMode = FadeMode.None; }