public static void ExitOverworld(bool totalUnload = true) { foreach (string str in NewMusicManager.audiolist.Keys) { if (((AudioSource)NewMusicManager.audiolist[str]) != null && str != "src") { GameObject.Destroy(((AudioSource)NewMusicManager.audiolist[str]).gameObject); } } NewMusicManager.audiolist.Clear(); NewMusicManager.audioname.Clear(); GameObject.Destroy(GameObject.Find("Player")); GameObject.Destroy(GameObject.Find("Canvas OW")); GameObject.Destroy(GameObject.Find("Canvas Two")); if (GameOverBehavior.gameOverContainerOw) { GameObject.Destroy(GameOverBehavior.gameOverContainerOw); } StaticInits.MODFOLDER = "@Title"; StaticInits.Initialized = false; StaticInits.InitAll(); UnitaleUtil.ResetOW(true); PlayerCharacter.instance.Reset(); Inventory.inventory.Clear(); Inventory.RemoveAddedItems(); ScriptWrapper.instances.Clear(); GlobalControls.isInFight = false; GlobalControls.isInShop = false; LuaScriptBinder.scriptlist.Clear(); LuaScriptBinder.ClearBattleVar(); LuaScriptBinder.Clear(); GameObject.Destroy(GameObject.Find("Main Camera OW")); }
public static bool TryCall(string func, DynValue[] param = null) { bool overworld = false; if (GameObject.Find("Main Camera OW")) { overworld = true; } if (!overworld) { try { if (LuaEnemyEncounter.script.GetVar(func) == null) { return(false); } if (param != null) { LuaEnemyEncounter.script.Call(func, param); } else { LuaEnemyEncounter.script.Call(func); } return(true); } catch (InterpreterException ex) { UnitaleUtil.DisplayLuaError(StaticInits.ENCOUNTER, ex.DecoratedMessage); return(true); } } else { return(false); } }
/// <summary> /// Launch the GameOver screen /// </summary> [CYFEventFunction] public void GameOver(DynValue deathText = null, string deathMusic = null) { PlayerCharacter.instance.HP = PlayerCharacter.instance.MaxHP; Transform rt = GameObject.Find("Player").GetComponent <Transform>(); rt.position = new Vector3(rt.position.x, rt.position.y, -1000); string[] deathTable = null; if (deathText != null) { deathTable = new string[deathText.Table.Length]; for (int i = 0; i < deathText.Table.Length; i++) { deathTable[i] = deathText.Table[i + 1].ToString(); } } GlobalControls.Music = UnitaleUtil.GetCurrentOverworldAudio().clip; PlayerOverworld.instance.enabled = false; UnitaleUtil.WriteInLogAndDebugger(GameObject.FindObjectOfType <GameOverBehavior>().name); GameObject.FindObjectOfType <GameOverBehavior>().StartDeath(deathTable, deathMusic); appliedScript.Call("CYFEventNextCommand"); }
/// <summary> /// Function that replaces the old Sprite Collision system by a Pixel-Perfect Collision system. /// </summary> /// <returns>true if there's a collision, otherwise false</returns> public bool HitTestPP() { if (selfAbs.Overlaps(PlayerController.instance.playerAbs)) { if (needUpdateTex) { texture = ((Texture2D)img.mainTexture).GetPixels32(); needUpdateTex = false; } if (ControlPanel.instance.MinimumAlpha == 0) { if (img.color.a == 0) { return(false); } } else if (img.color.a < ControlPanel.instance.MinimumAlpha) { return(false); } Vector2 positionPlayerFromProjectile = (Vector2)PlayerController.instance.self.position - selfAbs.position - (selfAbs.size + PlayerController.instance.playerAbs.size) / 2; return(UnitaleUtil.TestPP(playerHitbox, texture, ctrl.sprite.rotation, 8, img.mainTexture.height, new Vector2(ctrl.sprite.xscale, ctrl.sprite.yscale), positionPlayerFromProjectile, img.color.a)); } return(false); }
public void UpdateVariables() { AlMightyVariablesNum.Clear(); AlMightyVariablesStr.Clear(); AlMightyVariablesBool.Clear(); try { foreach (string key in LuaScriptBinder.GetAlMightyDictionary().Keys) { DynValue dv; LuaScriptBinder.GetAlMightyDictionary().TryGetValue(key, out dv); if (dv != null) { switch (dv.Type) { case DataType.Number: AlMightyVariablesNum.Add(key, dv.Number); break; case DataType.String: AlMightyVariablesStr.Add(key, dv.String); break; case DataType.Boolean: AlMightyVariablesBool.Add(key, dv.Boolean); break; default: UnitaleUtil.WriteInLogAndDebugger("SaveLoad: This DynValue can't be added to the save because it is unserializable."); break; } } } } catch { /* ignored */ } }
private static void loadAllFrom(string folderName, string script_prefix, bool needed) { string directoryPath = FileLoader.pathToModFile("Lua/" + folderName); DirectoryInfo dInfo = new DirectoryInfo(directoryPath); if (!dInfo.Exists) { if (needed) { UnitaleUtil.DisplayLuaError("mod loading", "You tried to load the mod \"" + StaticInits.MODFOLDER + "\" but it can't be found, or at least its \"Lua/" + folderName + "\" folder can't be found.\nAre you sure it exists?"); throw new CYFException("mod loading"); } return; } FileInfo[] fInfo = dInfo.GetFiles("*.lua", SearchOption.AllDirectories); foreach (FileInfo file in fInfo) { //UnitaleUtil.writeInLog(file.Name); string scriptName = FileLoader.getRelativePathWithoutExtension(directoryPath, file.FullName).ToLower(); string temp = ""; dict.TryGetValue(script_prefix + scriptName, out temp); if (dict.ContainsKey(script_prefix + scriptName) && temp == FileLoader.getTextFrom(file.FullName)) { continue; } else if (dict.ContainsKey(script_prefix + scriptName)) { dict.Remove(script_prefix + scriptName); } Set(script_prefix + scriptName, FileLoader.getTextFrom(file.FullName)); } }
/// <summary> /// Function that replaces the old Sprite Collision system by a Pixel-Perfect Collision system. /// </summary> /// <returns>true if there's a collision, otherwise false</returns> public virtual bool HitTestPP() { if (selfAbs.Overlaps(PlayerController.instance.playerAbs)) { if (needUpdateTex) { texture = ((Texture2D)GetComponent <Image>().mainTexture).GetPixels32(); needUpdateTex = false; } /*Rect rectProjectile = new Rect(new Vector2(selfAbs.x + selfAbs.width * (self.anchorMax.x - 0.5f), selfAbs.y + selfAbs.height * (self.anchorMax.y - 0.5f)), * new Vector2(selfAbs.width, selfAbs.height));*/ Color32[] tempPlayerHitbox = new Color32[Mathf.RoundToInt(PlayerController.instance.playerAbs.width) * Mathf.RoundToInt(PlayerController.instance.playerAbs.height)]; for (int i = 0; i < tempPlayerHitbox.Length; i++) { tempPlayerHitbox[i].a = 255; } Vector2 positionPlayerFromProjectile = (Vector2)PlayerController.instance.self.position - selfAbs.position - (selfAbs.size + PlayerController.instance.playerAbs.size) / 2; return(UnitaleUtil.TestPP(tempPlayerHitbox, texture, ctrl.sprite.rotation, Mathf.RoundToInt(PlayerController.instance.playerAbs.height), GetComponent <Image>().mainTexture.height, new Vector2(ctrl.sprite.xscale, ctrl.sprite.yscale), positionPlayerFromProjectile)); //Color32[] colors = UnitaleUtil.RotateMatrixOld(texture, ctrl.sprite.rotation, (int)GetComponent<Image>().sprite.rect.height, self.localScale, out sizeDelta); /*Texture2D tex = new Texture2D((int)sizeDelta.x, (int)sizeDelta.y); * tex.SetPixels32(colors); * tex.Apply(false); * byte[] bytes = tex.EncodeToPNG(); * File.WriteAllBytes(Application.dataPath + "/SavedScreen" + count++ +".png", bytes);*/ } return(false); }
public void Remove() { if (!isactive) { return; } Transform[] pcs = UnitaleUtil.GetFirstChildren(p.transform); for (int i = 1; i < pcs.Length; i++) { try { pcs[i].GetComponent <Projectile>().ctrl.Remove(); } catch { new LuaSpriteController(pcs[i].GetComponent <Image>()).Remove(); } } lastX = x; lastY = y; lastAbsX = absx; lastAbsY = absy; if (p.gameObject.GetComponent <KeyframeCollection>() != null) { Object.Destroy(p.gameObject.GetComponent <KeyframeCollection>()); } p.gameObject.GetComponent <Mask>().enabled = false; p.gameObject.GetComponent <RectMask2D>().enabled = false; spr.StopAnimation(); BulletPool.instance.Requeue(p); p = null; }
// NOTE: According to this guide (https://blogs.unity3d.com/2020/04/09/learn-to-save-memory-usage-by-improving-the-way-you-use-assetbundles/) // using AssetBundle.LoadFromFile (and LoadFromFileAsync) is only recommended when you intend to take out a lot of assets at once, or continually. // That is very not the goal for shaders in CYF, especially not Default shaders. // As such, instead of using AssetBundle.LoadFromFile, I'm using the page's recommended alternative, UnityWebRequestAssetBundle.GetAssetBundle. // If you wish to use the AssetBundle.LoadFromFile approach instead, uncomment the first line and comment the rest. private static AssetBundle retrieveAssetBundle(string fullPath) { //return AssetBundle.LoadFromFile(fullPath); try { UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(new Uri(fullPath).AbsoluteUri.Replace("+", "%2B")); uwr.SendWebRequest(); while (!uwr.isDone) { } // hold up a bit while it's loading; delay isn't noticeable and loading will fail otherwise AssetBundle content = DownloadHandlerAssetBundle.GetContent(uwr); if (content == null) { throw new CYFException("Error while loading the shader \"" + fullPath + "\".\n\nIt's likely that you have two identical shader AssetBundles loaded at once."); } if (uwr.error != null) { throw new CYFException(uwr.error); } return(content); } catch (CYFException e) { UnitaleUtil.DisplayLuaError("loading a shader", e.Message); } catch (Exception e) { UnitaleUtil.DisplayLuaError("loading a shader", "This is a " + e.GetType() + " error. Please show this screen to a developer.\n\n" + e.Message + "\n\n" + e.StackTrace); } return(null); }
public void Dust(bool playDust = true, bool removeObject = false) { if (tag == "enemy" || tag == "bubble") { throw new CYFException("sprite.Dust(): You can't dust a " + tag + "'s sprite!"); } GameObject go = Object.Instantiate(Resources.Load <GameObject>("Prefabs/MonsterDuster")); go.transform.SetParent(UIController.instance.psContainer.transform); if (playDust) { UnitaleUtil.PlaySound("DustSound", AudioClipRegistry.GetSound("enemydust")); } img.GetComponent <ParticleDuplicator>().Activate(this); if (img.gameObject.name == "player") { return; } img.SetActive(false); if (removeObject) { Remove(); } }
/// <summary> /// Launch the GameOver screen /// </summary> [CYFEventFunction] public void GameOver(DynValue deathText = null, string deathMusic = null) { PlayerCharacter.instance.HP = PlayerCharacter.instance.MaxHP; Transform rt = GameObject.Find("Player").GetComponent <Transform>(); rt.position = new Vector3(rt.position.x, rt.position.y, -1000); string[] deathTable = null; if (deathText != null) { if (deathText.Type == DataType.Table) { deathTable = new string[deathText.Table.Length]; for (int i = 0; i < deathText.Table.Length; i++) { deathTable[i] = deathText.Table[i + 1].ToString(); } } else if (deathText.Type == DataType.String) { deathTable = new string[] { deathText.String } } ; else { throw new CYFException("General.GameOver: deathText needs to be a table or a string."); } } GlobalControls.Music = UnitaleUtil.GetCurrentOverworldAudio().clip; PlayerOverworld.instance.enabled = false; GameObject.FindObjectOfType <GameOverBehavior>().StartDeath(deathTable, deathMusic); appliedScript.Call("CYFEventNextCommand"); }
public static void calcDataRoot() { DirectoryInfo rootInfo = new DirectoryInfo(Application.dataPath); string SysDepDataRoot = rootInfo.FullName; while (true) { DirectoryInfo[] dfs = rootInfo.GetDirectories(); foreach (DirectoryInfo df in dfs) { if (df.FullName == Path.Combine(SysDepDataRoot, "Mods")) { DataRoot = SysDepDataRoot; return; } } try { rootInfo = new DirectoryInfo(rootInfo.Parent.FullName); } catch { UnitaleUtil.DisplayLuaError("CYF's Startup", "The engine detected no Mods folder in your files: are you sure that it exists?"); return; } SysDepDataRoot = rootInfo.FullName; //Debug.Log(SysDepDataRoot); } //if (Application.platform == RuntimePlatform.OSXPlayer) /*OSX has stuff bundled in .app things*/ SysDepDataRoot = rootInfo.Parent.Parent.FullName; //else if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor) { /*everything is fine*/ } //else SysDepDataRoot = rootInfo.Parent.FullName; }
public static bool TryCall(string func, DynValue[] param = null) { if (UnitaleUtil.IsOverworld) { return(false); } try { if (EnemyEncounter.script.GetVar(func) == null) { return(false); } if (param != null) { EnemyEncounter.script.Call(func, param); } else { EnemyEncounter.script.Call(func); } return(true); } catch (InterpreterException ex) { UnitaleUtil.DisplayLuaError(StaticInits.ENCOUNTER, UnitaleUtil.FormatErrorSource(ex.DecoratedMessage, ex.Message) + ex.Message); return(true); } }
public void Hurt(int damage) { if (damage >= 0) { UnitaleUtil.PlaySound("HurtSound", AudioClipRegistry.GetSound("hurtsound"), 0.65f); } else { UnitaleUtil.PlaySound("HurtSound", AudioClipRegistry.GetSound("healsound"), 0.65f); } if (-damage + player.HP > player.MaxHP) { player.HP = player.MaxHP; } else if (-damage + player.HP <= 0) { player.HP = 1; } else { player.HP -= damage; } appliedScript.Call("CYFEventNextCommand"); }
/// <summary> /// Displays a text. /// </summary> /// <param name="texts"></param> /// <param name="formatted"></param> /// <param name="mugshots"></param> [CYFEventFunction] public void SetDialog(DynValue texts, bool formatted = true, DynValue mugshots = null, DynValue forcePosition = null) { // Unfortunately, either C# or MoonSharp (don't know which) has a ridiculous limit in place // Calling `SetDialog({""}, true, nil, true)` fails to pass the final argument if (mugshots != null && mugshots.Type == DataType.Table && forcePosition != null) { PlayerOverworld.instance.UIPos = forcePosition.Type == DataType.Boolean ? (forcePosition.Boolean == true ? 2 : 1) : 0; } else { PlayerOverworld.instance.UIPos = 0; } if (EventManager.instance.coroutines.ContainsKey(appliedScript) && EventManager.instance.script != appliedScript) { UnitaleUtil.DisplayLuaError(EventManager.instance.events[EventManager.instance.actualEventIndex].name, "General.SetDialog: You can't use that function in a coroutine."); return; } else if (EventManager.instance.LoadLaunched) { UnitaleUtil.DisplayLuaError(EventManager.instance.events[EventManager.instance.actualEventIndex].name, "General.SetDialog: You can't use that function in a page 0 function."); return; } TextMessage[] textmsgs = new TextMessage[texts.Table.Length]; for (int i = 0; i < texts.Table.Length; i++) { textmsgs[i] = new TextMessage(texts.Table.Get(i + 1).String, formatted, false, mugshots != null ? mugshots.Type == DataType.Table ? mugshots.Table.Get(i + 1) : mugshots : null); } textmgr.SetTextQueue(textmsgs); textmgr.transform.parent.parent.SetAsLastSibling(); }
public override void EndWave(bool death = false) { Table t = script["Wave"].Table; if (!death) { foreach (object obj in t.Keys) { try { ((ScriptWrapper)t[obj]).Call("EndingWave"); } catch { UnitaleUtil.DisplayLuaError(StaticInits.ENCOUNTER, "You shouldn't override Wave, now you get an error :P"); } } } if (!GlobalControls.retroMode) { foreach (LuaProjectile p in FindObjectsOfType <LuaProjectile>()) { if (!p.ctrl.isPersistent) { p.ctrl.Remove(); } } } if (!death) { CallOnSelfOrChildren("DefenseEnding"); } ArenaManager.instance.resetArena(); EncounterText = script.GetVar("encountertext").String; EraseDust(); script.SetVar("Wave", DynValue.NewTable(new Table(null))); // Projectile.Z_INDEX_NEXT = Projectile.Z_INDEX_INITIAL; // doesn't work yet }
/// <summary> /// Function that sets an event's animation prefix. /// If the header itself matches an animation this event has, it will play the animation instead of using it as a prefix. /// </summary> /// <param name="name"></param> /// <param name="anim"></param> [CYFEventFunction] public void SetAnimHeader(string name, string anim) { for (int i = 0; i < EventManager.instance.events.Count || name == "Player"; i++) { GameObject go = null; try { go = EventManager.instance.events[i]; } catch { } if (name == go.name || name == "Player") { if (name == "Player") { go = GameObject.Find("Player"); } if (go == null) { throw new CYFException("Event.SetAnimHeader: The given event doesn't exist."); } CYFAnimator animator = go.GetComponent <CYFAnimator>(); if (animator == null) { throw new CYFException("Event.SetAnimHeader: The given event doesn't have a CYFAnimator component."); } if (animator.AnimExists(animator.specialHeader)) { animator.movementDirection = 2; } go.GetComponent <CYFAnimator>().specialHeader = anim; appliedScript.Call("CYFEventNextCommand"); return; } } UnitaleUtil.WriteInLogAndDebugger("Event.SetAnimHeader: The name you entered in the function isn't an event's name. Did you forget to add the 'Event' tag?"); appliedScript.Call("CYFEventNextCommand"); }
IEnumerator NewGame() { SpriteRenderer blank = GameObject.Find("Blank").GetComponent <SpriteRenderer>(); while (blank.color.a <= 1) { if (tmName.transform.localScale.x < 3) { tmName.transform.localScale = new Vector3(tmName.transform.localScale.x + 0.01f, tmName.transform.localScale.y + 0.01f, 1); tmName.transform.localPosition = new Vector3(actualX - (((tmName.transform.localScale.x - 1) * diff) / 2), actualY - (((tmName.transform.localScale.x - 1) * diff) / 6), tmName.transform.localPosition.z); } blank.color = new Color(blank.color.r, blank.color.g, blank.color.b, blank.color.a + 0.003f); yield return(0); } while (Camera.main.GetComponent <AudioSource>().isPlaying) { yield return(0); } PlayerCharacter.instance.Reset(false); LuaScriptBinder.ClearVariables(); GlobalControls.GameMapData.Clear(); Inventory.inventory.Clear(); GameObject.DontDestroyOnLoad(gameObject); UnitaleUtil.ResetOW(); SceneManager.LoadScene("TransitionOverworld"); yield return(0); //yield return Application.isLoadingLevel; if (GameObject.Find("Main Camera")) { GameObject.Destroy(GameObject.Find("Main Camera")); } GameObject.Destroy(gameObject); }
///<summary> ///Overrideable item handler on a per-encounter basis. Should return true if a custom action is executed for the given item. ///</summary> ///<param name="item">Item to be checked for custom action</param> ///<returns>true if a custom action should be executed for given item, false if the default action should happen</returns> //public override bool CustomItemHandler(UnderItem item) { return CallOnSelfOrChildren("HandleItem", new DynValue[] { DynValue.NewString(item.Name) }); } public override void UpdateWave() { string currentScript = ""; try { for (int i = 0; i < waves.Length; i++) { currentScript = waveNames[i]; try { waves[i].script.Call(waves[i].script.Globals["Update"]); } catch (InterpreterException ex) { UnitaleUtil.DisplayLuaError(currentScript, ex.DecoratedMessage); return; } catch (Exception ex) { if (!GlobalControls.retroMode) { if (waves[i].script.Globals["Update"] == null) { UnitaleUtil.DisplayLuaError(currentScript, "All the wave scripts need an Update() function!"); } else { UnitaleUtil.DisplayLuaError(currentScript, "This error is a " + ex.GetType().ToString() + " error.\nPlease send this error to the main dev.\n\n" + ex.Message + "\n\n" + ex.StackTrace); } } return; } } } catch (InterpreterException ex) { UnitaleUtil.DisplayLuaError(currentScript, ex.DecoratedMessage); return; } }
public void setHP(float newhp, bool forced = false) { if (newhp <= 0) { EventManager.instance.luaGeneralOw.GameOver(); return; } float CheckedHP = PlayerCharacter.instance.HP; UnitaleUtil.PlaySound("CollisionSoundChannel", AudioClipRegistry.GetSound(CheckedHP - newhp >= 0 ? "hurtsound" : "healsound").name); newhp = Mathf.Round(newhp * Mathf.Pow(10, ControlPanel.instance.MaxDigitsAfterComma)) / Mathf.Pow(10, ControlPanel.instance.MaxDigitsAfterComma); if (forced) { CheckedHP = newhp > PlayerCharacter.instance.MaxHP * 1.5 ? (int)(PlayerCharacter.instance.MaxHP * 1.5) : newhp; } else { CheckedHP = newhp > PlayerCharacter.instance.MaxHP ? PlayerCharacter.instance.MaxHP : newhp; } if (CheckedHP > ControlPanel.instance.HPLimit) { CheckedHP = ControlPanel.instance.HPLimit; } PlayerCharacter.instance.HP = CheckedHP; }
public void setMaxHP(int value) { if (value == PlayerCharacter.instance.MaxHP) { return; } if (value <= 0) { setHP(0); return; } if (value > ControlPanel.instance.HPLimit) { value = ControlPanel.instance.HPLimit; } else if (PlayerCharacter.instance.HP > value) { PlayerCharacter.instance.HP = value; } else { UnitaleUtil.PlaySound("CollisionSoundChannel", AudioClipRegistry.GetSound("healsound").name); } PlayerCharacter.instance.MaxHPShift = value - PlayerCharacter.instance.BasisMaxHP; }
public static void BattleDialog(DynValue arg) { if (UIController.instance == null) { UnitaleUtil.WriteInLogAndDebugger("[WARN]BattleDialog can only be used as early as EncounterStarting."); } else { UIController.instance.battleDialogued = true; TextMessage[] msgs = null; if (arg.Type == DataType.String) { msgs = new TextMessage[] { new RegularMessage(arg.String) } } ; else if (arg.Type == DataType.Table) { msgs = new TextMessage[arg.Table.Length]; for (int i = 0; i < arg.Table.Length; i++) { msgs[i] = new RegularMessage(arg.Table.Get(i + 1).String); } } else { UnitaleUtil.DisplayLuaError("BattleDialog", "You need to input a non-empty array or a string here." + "\n\nIf you're sure that you've entered what's needed, you may contact the dev."); } UIController.instance.ActionDialogResult(msgs, UIController.UIState.ENEMYDIALOGUE); } }
public void SaveGameVariables() { try { LuaScriptBinder.Set(null, "PlayerPosX", DynValue.NewNumber(GameObject.Find("Player").transform.position.x)); LuaScriptBinder.Set(null, "PlayerPosY", DynValue.NewNumber(GameObject.Find("Player").transform.position.y)); LuaScriptBinder.Set(null, "PlayerPosZ", DynValue.NewNumber(GameObject.Find("Player").transform.position.z)); } catch { LuaScriptBinder.Set(null, "PlayerPosX", DynValue.NewNumber(SaveLoad.savedGame.playerVariablesNum["PlayerPosX"])); LuaScriptBinder.Set(null, "PlayerPosY", DynValue.NewNumber(SaveLoad.savedGame.playerVariablesNum["PlayerPosY"])); LuaScriptBinder.Set(null, "PlayerPosZ", DynValue.NewNumber(SaveLoad.savedGame.playerVariablesNum["PlayerPosZ"])); } playerHeader = CYFAnimator.specialPlayerHeader; string mapName; if (UnitaleUtil.MapCorrespondanceList.ContainsKey(SceneManager.GetActiveScene().name)) { mapName = UnitaleUtil.MapCorrespondanceList[SceneManager.GetActiveScene().name]; } else if (GlobalControls.nonOWScenes.Contains(SceneManager.GetActiveScene().name) || GlobalControls.isInFight) { mapName = SaveLoad.savedGame.lastScene; } else { mapName = SceneManager.GetActiveScene().name; } lastScene = mapName; soundDictionary = MusicManager.hiddenDictionary; controlpanel = ControlPanel.instance; player = PlayerCharacter.instance; inventory.Clear(); foreach (UnderItem item in Inventory.inventory) { inventory.Add(item.Name); } try { foreach (string key in LuaScriptBinder.GetSavedDictionary().Keys) { DynValue dv; LuaScriptBinder.GetSavedDictionary().TryGetValue(key, out dv); switch (dv.Type) { case DataType.Number: playerVariablesNum.Add(key, dv.Number); break; case DataType.String: playerVariablesStr.Add(key, dv.String); break; case DataType.Boolean: playerVariablesBool.Add(key, dv.Boolean); break; default: UnitaleUtil.WriteInLogAndDebugger("SaveLoad: This DynValue can't be added to the save because it is unserializable."); break; } } } catch { } mapInfos = GlobalControls.MapData; }
// Use this for initialization void Start() { FindObjectOfType <Fading>().BeginFade(-1); tmMain = GameObject.Find("TextManager Main").GetComponent <TextManager>(); tmChoice = GameObject.Find("TextManager Choice").GetComponent <TextManager>(); tmInfo = GameObject.Find("TextManager Info").GetComponent <TextManager>(); tmBigTalk = GameObject.Find("TextManager BigTalk").GetComponent <TextManager>(); tmGold = GameObject.Find("TextManager Gold").GetComponent <TextManager>(); tmItem = GameObject.Find("TextManager Item").GetComponent <TextManager>(); tmInfoParent = tmInfo.transform.parent.parent.gameObject; tmBigTalk.SetTextQueue(new TextMessage[] { new TextMessage("[noskipatall][novoice]", false, true) }); utHeart = GameObject.Find("utHeart"); EnableBigText(false); if (scriptName == null) { throw new CYFException("You must give a valid script name to the function General.EnterShop()"); } script = new ScriptWrapper() { scriptname = scriptName }; string scriptText = ScriptRegistry.Get(ScriptRegistry.SHOP_PREFIX + scriptName); if (scriptText == null) { throw new CYFException("You must give a valid script name to the function General.EnterShop()"); } try { script.DoString(scriptText); script.SetVar("background", UserData.Create(new LuaSpriteController(GameObject.Find("Background").GetComponent <Image>()))); script.script.Globals["Interrupt"] = ((Action <DynValue, string>)Interrupt); script.script.Globals["CreateSprite"] = (Func <string, string, int, DynValue>)SpriteUtil.MakeIngameSprite; script.script.Globals["CreateLayer"] = (Action <string, string, bool>)SpriteUtil.CreateLayer; script.script.Globals["CreateText"] = (Func <Script, DynValue, DynValue, int, string, int, LuaTextManager>)LuaScriptBinder.CreateText; TryCall("Start"); tmMain.SetCaller(script); tmChoice.SetCaller(script); tmInfo.SetCaller(script); tmBigTalk.SetCaller(script); tmMain.SetTextQueue(new TextMessage[] { new TextMessage("[noskipatall][linespacing:11]" + script.GetVar("maintalk").String, true, false) }); tmChoice.SetTextQueue(new TextMessage[] { new TextMessage("[noskipatall][novoice][font:uidialoglilspace][linespacing:9] Buy\n Sell\n Talk\n Exit", false, true) }); tmGold.SetTextQueue(new TextMessage[] { new TextMessage("[noskipatall][novoice]" + PlayerCharacter.instance.Gold + "G", false, true) }); tmItem.SetTextQueue(new TextMessage[] { new TextMessage("[noskipatall][novoice]" + Inventory.inventory.Count + "/8", false, true) }); tmInfo.SetTextQueue(new TextMessage[] { new TextMessage("[noskipatall][novoice]", false, true) }); Camera.main.GetComponent <AudioSource>().clip = AudioClipRegistry.GetMusic(script.GetVar("music").String); Camera.main.GetComponent <AudioSource>().time = 0; Camera.main.GetComponent <AudioSource>().Play(); SetPlayerOnSelection(); } catch (InterpreterException ex) { UnitaleUtil.DisplayLuaError(scriptName, ex.DecoratedMessage != null ? UnitaleUtil.FormatErrorSource(ex.DecoratedMessage, ex.Message) + ex.Message : ex.Message); } catch (Exception ex) { UnitaleUtil.DisplayLuaError(scriptName, "Unknown error. Usually means you're missing a sprite.\nSee documentation for details.\nStacktrace below in case you wanna notify a dev.\n\nError: " + ex.Message + "\n\n" + ex.StackTrace); } }
string BuildTalkString() { DynValue talks, talkResults; try { talks = script.GetVar("talklist").Table.Get(1); talkResults = script.GetVar("talklist").Table.Get(2); } catch { UnitaleUtil.DisplayLuaError("Creating the Talk menu", "The variable talklist must be an array which contains two other arrays."); return(""); } string result = "[font:uidialoglilspace][linespacing:11]"; if (talks.Type == DataType.Table) { mainName = new string[talks.Table.Length]; mainInfo = new DynValue[talks.Table.Length]; for (int i = 0; i < talks.Table.Length; i++) { mainName[i] = talks.Table.Get(i + 1).String; result += " " + mainName[i] + "\n"; mainInfo[i] = talkResults.Table.Get(i + 1); } } else { UnitaleUtil.DisplayLuaError("Creating the Talk menu", "The variable talklist must be an array which contains two other arrays."); return(""); } return(result + " Exit"); }
public static LuaTextManager CreateText(Script scr, DynValue text, DynValue position, int textWidth, string layer = "BelowPlayer", int bubbleHeight = -1) { GameObject go = UnityEngine.Object.Instantiate(Resources.Load <GameObject>("Prefabs/CstmTxtContainer")); LuaTextManager luatm = go.GetComponentInChildren <LuaTextManager>(); go.GetComponent <RectTransform>().position = new Vector2((float)position.Table.Get(1).Number, (float)position.Table.Get(2).Number); UnitaleUtil.GetChildPerName(go.transform, "BubbleContainer").GetComponent <RectTransform>().pivot = new Vector2(0, 1); UnitaleUtil.GetChildPerName(go.transform, "BubbleContainer").GetComponent <RectTransform>().localPosition = new Vector2(-12, 8); UnitaleUtil.GetChildPerName(go.transform, "BubbleContainer").GetComponent <RectTransform>().sizeDelta = new Vector2(textWidth + 20, 100); //Used to set the borders UnitaleUtil.GetChildPerName(go.transform, "BackHorz").GetComponent <RectTransform>().sizeDelta = new Vector2(textWidth + 20, 100 - 20 * 2); //BackHorz UnitaleUtil.GetChildPerName(go.transform, "BackVert").GetComponent <RectTransform>().sizeDelta = new Vector2(textWidth - 20, 100); //BackVert UnitaleUtil.GetChildPerName(go.transform, "CenterHorz").GetComponent <RectTransform>().sizeDelta = new Vector2(textWidth + 16, 96 - 16 * 2); //CenterHorz UnitaleUtil.GetChildPerName(go.transform, "CenterVert").GetComponent <RectTransform>().sizeDelta = new Vector2(textWidth - 16, 96); //CenterVert luatm.SetFont(SpriteFontRegistry.UI_MONSTERTEXT_NAME, true); foreach (ScriptWrapper scrWrap in ScriptWrapper.instances) { if (scrWrap.script == scr) { luatm.SetCaller(scrWrap); break; } } luatm.layer = layer; luatm.textWidth = textWidth; luatm.bubbleHeight = bubbleHeight; luatm.ShowBubble(); if (text == DynValue.Nil || text.Table.Length == 0) { text = null; } luatm.SetText(text); return(luatm); }
public static AudioClip tryLoad(string key) { string k = key; key = key.ToLower(); if (dictMod.ContainsKey(key)) { dict[key] = FileLoader.getAudioClip(currentPath, dictMod[key].FullName); } else if (dictDefault.ContainsKey(key)) { dict[key] = FileLoader.getAudioClip(currentPath, dictDefault[key].FullName); } else { if (GlobalControls.retroMode) { UnitaleUtil.Warn("The audio file \"" + k + "\" doesn't exist."); } else { throw new CYFException("Attempted to load the audio file \"" + k + "\" from either a mod or default directory, but it was missing in both."); } return(null); } return(dict[key]); }
/*private static void loadAllFrom(string directoryPath, bool mod = false) { * DirectoryInfo dInfo = new DirectoryInfo(directoryPath); * FileInfo[] fInfo = dInfo.GetFiles("*.*", SearchOption.AllDirectories).Where(file => extensions.Contains(file.Extension)).ToArray(); * foreach (FileInfo file in fInfo) { * string voiceName = FileLoader.getRelativePathWithoutExtension(directoryPath, file.FullName).ToLower(); * AudioClip temp; * dict.TryGetValue(voiceName, out temp); * * if (dict.ContainsKey(voiceName) && temp == FileLoader.getAudioClip(directoryPath, file.FullName) &&!mod) * continue; * * //string voiceName = FileLoader.getRelativePathWithoutExtension(directoryPath, file.FullName).ToLower(); * //if (dict.ContainsKey(voiceName)) * // continue; * FileLoader.getAudioClip(directoryPath, file.FullName); * } * }*/ private static void loadAllFrom(string directoryPath, bool mod = false) { DirectoryInfo dInfo = new DirectoryInfo(directoryPath); if (!dInfo.Exists) { UnitaleUtil.DisplayLuaError("mod loading", "You tried to load the mod \"" + StaticInits.MODFOLDER + "\" but it can't be found.\nAre you sure it exists?"); throw new CYFException("mod loading"); } FileInfo[] fInfo = dInfo.GetFiles("*.*", SearchOption.AllDirectories).Where(file => extensions.Contains(file.Extension)).ToArray(); if (mod) { currentPath = directoryPath; dictMod.Clear(); foreach (FileInfo file in fInfo) { dictMod[FileLoader.getRelativePathWithoutExtension(directoryPath, file.FullName).ToLower()] = file; } } else { dictDefault.Clear(); foreach (FileInfo file in fInfo) { dictDefault[FileLoader.getRelativePathWithoutExtension(directoryPath, file.FullName).ToLower()] = file; } } }
public void setHP(float newhp, bool forced = false) { if (newhp <= 0) { GameOverBehavior gob = GameObject.FindObjectOfType <GameOverBehavior>(); if (!MusicManager.IsStoppedOrNull(PlayerOverworld.audioKept)) { gob.musicBefore = PlayerOverworld.audioKept; gob.music = gob.musicBefore.clip; gob.musicBefore.Stop(); } else if (!MusicManager.IsStoppedOrNull(Camera.main.GetComponent <AudioSource>())) { gob.musicBefore = Camera.main.GetComponent <AudioSource>(); gob.music = gob.musicBefore.clip; gob.musicBefore.Stop(); } else { gob.musicBefore = null; gob.music = null; } player.HP = 0; gob.gameObject.transform.SetParent(null); GameObject.DontDestroyOnLoad(gob.gameObject); RectTransform rt = gob.gameObject.GetComponent <RectTransform>(); rt.position = new Vector3(rt.position.x, rt.position.y, -1000); gob.gameObject.GetComponent <GameOverBehavior>().StartDeath(); return; } float CheckedHP = player.HP; if (CheckedHP - newhp >= 0) { UnitaleUtil.PlaySound("CollisionSoundChannel", AudioClipRegistry.GetSound("hurtsound").name); } else { UnitaleUtil.PlaySound("CollisionSoundChannel", AudioClipRegistry.GetSound("healsound").name); } newhp = Mathf.Round(newhp * Mathf.Pow(10, ControlPanel.instance.MaxDigitsAfterComma)) / Mathf.Pow(10, ControlPanel.instance.MaxDigitsAfterComma); if (forced) { CheckedHP = newhp > player.MaxHP * 1.5 ? (int)(player.MaxHP * 1.5) : newhp; } else { CheckedHP = newhp > player.MaxHP ? player.MaxHP : newhp; } if (CheckedHP > ControlPanel.instance.HPLimit) { CheckedHP = ControlPanel.instance.HPLimit; } player.HP = CheckedHP; }
public static Sprite[] AtlasFromXml(XmlNode sheetNode, Sprite source) { try { return((from XmlNode child in sheetNode.ChildNodes where child.Name.Equals("sprite") select SpriteWithXml(child, source)).ToArray()); } catch (Exception ex) { UnitaleUtil.DisplayLuaError("[XML document]", "One of the sprites' XML documents was invalid. This could be a corrupt or edited file.\n\n" + ex.Message); return(null); } }