//Function called from the MainMenu scene to continue the most recent save public void ContinueGame() { //If the most recent save doesn't exist, we're trying to load settings that don't exist if (!PlayerPrefs.HasKey("MostRecentSave")) { Debug.Log("ContinueGame, MostRecentSave doesn't exist"); return; } else if (PlayerPrefs.GetString("MostRecentSave") == "") { Debug.Log("ContinueGame, MostRecentSave is empty"); return; } else if (!System.IO.Directory.Exists(Application.persistentDataPath + PlayerPrefs.GetString("MostRecentSave"))) { Debug.Log("ContinueGame, MostRecentSave folder directory doesn't exist"); return; } //Loading the folder name for the most recent save so we can "Continue" this.saveFolder = PlayerPrefs.GetString("MostRecentSave"); //Telling the map generator to load our existing level this.loadType = LevelLoadType.LoadLevel; //Transitioning to the gameplay level //this.GetComponent<GoToLevel>().LoadLevelByName(this.gameplayLevelName); EVTData transitionEVT = new EVTData(); transitionEVT.sceneTransition = new SceneTransitionEVT(this.gameplayLevelName, 0.5f, 1); EventManager.TriggerEvent(SceneTransitionEVT.eventNum, transitionEVT); }
//Function called from the New Game screen in the main menu. Starts the process of creating a new map public void StartNewGame() { //Determining if new items will be available in this game based on the seed value if (this.GetComponent <RandomSeedGenerator>().seed == "") { this.allowNewUnlockables = true; } else { this.allowNewUnlockables = false; } //Making sure our save folder name is valid this.saveFolder = SaveLoadManager.globalReference.CreateNewSaveFolder(); //Telling the map generator to create a new level instead of loading one from a save this.loadType = LevelLoadType.GenerateNewLevel; //Saving the current save folder name so we know which game was played last. Used for "Continuing" PlayerPrefs.SetString("MostRecentSave", GameData.globalReference.saveFolder); //Transitioning to the gameplay level //this.GetComponent<GoToLevel>().LoadLevelByName(this.gameplayLevelName); EVTData transitionEVT = new EVTData(); transitionEVT.sceneTransition = new SceneTransitionEVT(this.gameplayLevelName, 0.5f, 1); EventManager.TriggerEvent(SceneTransitionEVT.eventNum, transitionEVT); }
/* Function called from the EventManager.cs using the multiTrackEVT delegate event * Adds a gameobject to the list of ObjectSelected*/ private void TrackMultipleObj(EVTData data_) { //Makes sure that the only objects that can be multi-selected are ships if (data_.objectSelected.objectSelected.GetComponent <Ship>() == null || objectSelected.Count >= 12) { return; } //If the first object selected wasn't a ship, removes it from the selection before adding the new ship if (objectSelected.Count > 0 && objectSelected[0].GetComponent <Ship>() == null) { this.ClearSelected(); } //If the new object wasn't already selected, adds it to the selection list if (!objectSelected.Contains(data_.objectSelected.objectSelected)) { objectSelected.Add(data_.objectSelected.objectSelected); } //If the object was selected, deselects it else { objectSelected.Remove(data_.objectSelected.objectSelected); } }
/* Function called from the EventManager.cs using the trackObjectEVT delegate event * Selects a single object to track*/ private void TrackSelectedObj(EVTData data_) { //Clears the current selection of game objects this.ClearSelected(); //Adds the newly selected objects to the selection list objectSelected.Add(data_.objectSelected.objectSelected); }
//Function called from the toggleLoadEVT delegate private void ToggleLoad(EVTData data_) { //Making sure the load data is valid if (data_ == null || data_.loadData == null) { return; } //If the load is starting if (data_.loadData.startingLoad) { //Enabling our loading bar and resetting the value to 0 this.loadingUIObject.SetActive(true); this.loadingBar.value = 0; //Setting the total number of load updates this.totalUpdates = data_.loadData.totalLoadUpdates; this.currentUpdates = 0; } //If we're still loading else { //Increasing our number of current updates by 1 this.currentUpdates += 1; //Setting the loading bar slider to update the bar this.loadingBar.value = (this.currentUpdates * 1f) / (this.totalUpdates * 1f); //If we've hit the last update, we disable the loading bar if (this.currentUpdates >= this.totalUpdates) { this.loadingUIObject.SetActive(false); } } }
//Function called when the player cursor is over this object private void OnMouseOver() { //Does nothing if the player mouse input is disabled if (MouseData.isMouseDisabled) { return; } //Clears the current selection if this object is left-clicked by itself if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject() && !Input.GetKey(KeyCode.LeftShift) && !Input.GetKey(KeyCode.LeftAlt)) { EventManager.TriggerEvent("ClearSelected"); } //If right clicked over, sends an event with the click coords for selected objects to move to if (Input.GetMouseButtonDown(1)) { //Creates a raycast from the mouse to the world position where it collides with this object RaycastHit clickCast; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out clickCast, 3000.0f)) { //If the raycast hits something, dispatches a delegate event with the point hit if (clickCast.point != null) { EVTData clickData = new EVTData(); clickData.mapClick = new MapClickEVT(clickCast.point); EventManager.TriggerEvent("MapClick", clickData); } } } }
//Function inherited from MapLocation.cs that loads the city UI when the player travels there public override void TravelToLocation() { //Sending this city's data to the HUDLocationScreen.cs via the event manager EVTData locationEvent = new EVTData(); locationEvent.openLocation = new OpenLocationEVT(OpenLocationEVT.LocationType.City, this); EventManager.TriggerEvent(OpenLocationEVT.eventNum, locationEvent); }
//Function called externally. Causes damage to this object and will destroy it if its health goes to 0 public void Damage(int damageTaken_, GameObject attacker_) { //Can't inflict negative damage if (damageTaken_ < 0) { return; } //Subtracts damage from this owner's shield if they have one if (GetComponent <ShieldTracker>() != null) { //Any remaining damage is returned and dealt to this object's health this.currentHealth -= this.GetComponent <ShieldTracker>().Damage(damageTaken_); } //If there is no shield, damage is dealt directly to HP else { this.currentHealth -= damageTaken_; } //When the health drops below 0 it's destroyed if (this.currentHealth <= 0) { this.currentHealth = 0; //Dispatches an event saying that this object was destroyed and who the attacker was EVTData destroyedEVT = new EVTData(); destroyedEVT.objectDestroyed = new ObjectDestroyedEVT(attacker_, this.gameObject); EventManager.TriggerEvent("ObjectWasDestroyed", destroyedEVT); } }
//Function called externally from LandTile.cs to initiate combat public void InitiateCombat(LandType combatLandType_, PartyGroup charactersInCombat_, EnemyEncounter encounter_) { //Creating the event data that we'll pass to the TransitionFade through the EventManager EVTData transitionEvent = new EVTData(); //Setting the transition to take 0.5 sec to fade out, stay on black for 1 sec, fade in for 0.5 sec, and call our initialize event to display the combat canvas transitionEvent.combatTransition = new CombatTransitionEVT(true, 0.5f, 1, 0.5f, this.combatInitializeEvent); //Invoking the transition event through the EventManager EventManager.TriggerEvent(CombatTransitionEVT.eventNum, transitionEvent); //Resetting all of the combat tiles to their default values this.tileHandler.ResetCombatTiles(); //Setting the combat positions for the player characters and enemies based on their distances this.characterHandler.InitializeCharactersForCombat(charactersInCombat_, encounter_); //Resetting the combat UI and cameras this.initiativeHandler.ResetForCombatStart(); this.uiHandler.ResetForCombatStart(); this.cameraHandler.ResetForCombatStart(); //Setting the state to start increasing initiatives after a brief wait this.SetWaitTime(3, CombatState.IncreaseInitiative); //Looping through and copying the loot table from the encounter this.lootTable = new List <EncounterLoot>(); foreach (EncounterLoot drop in encounter_.lootTable) { EncounterLoot loot = new EncounterLoot(); loot.lootItem = drop.lootItem; loot.dropChance = drop.dropChance; loot.stackSizeMinMax = drop.stackSizeMinMax; this.lootTable.Add(loot); } }
//Function called externally when this player takes damage public void DamagePlayer(int damageDealt_ = 0) { //Nothing happens if the damage dealt is below 0. if (damageDealt_ < 0) { return; } //Nothing happens if this player is currently invulnerable if (this.invulnerableCounter > 0) { return; } this.currentHealth -= damageDealt_; //If the player's health hits 0, they die if (this.currentHealth <= 0) { //Starts the death sequence for this player this.currentHealth = 0; this.invulnerableCounter = this.invulnerableTime; this.respawnCounter = this.respawnTime; //Dispatches a player death event saying that this player died EVTData deathEVT = new EVTData(); deathEVT.playerDeath = new PlayerDeathEVT(this.playerIDTag.playerID, this.playerIDTag.playerTeam); Manager_EventManager.TriggerEvent(PlayerDeathEVT.eventName, deathEVT); } }
//Overrides the base function from Power_DefaultLogic. Called from the Event Manager through the ActivateEVT delegate event protected override void ActivatePower(EVTData data_) { //This power won't activate if the activating player wasn't this one, if it was the other slot, or if this is on cooldown if (data_.playerPowerActivate.playerID != this.ownerPlayer || data_.playerPowerActivate.slot != this.slot || this.rechargeCounter > 0 || this.currentFireTime > 0) { return; } //Spawns the projectile to fire this.FireProjectile(); //Forces the player backward to give this gun recoil this.Recoil(); //Subtracts a projectile from the current clip this.projectilesInClip -= 1; //If we still have projectiles in the clip, the fire speed cooldown is started if (this.projectilesInClip > 0) { this.currentFireTime = this.fireSpeed; } //If no projectiles are left, then the recharge counter is started (basically reload time) else { this.rechargeCounter = this.rechargeTime; } }
//Function called externally. Tells the player camera to stop interpolating to follow an object public void CameraStopFollowingThisObj() { EVTData trackevt = new EVTData(); trackevt.cameraTrackObject = new CameraTrackObjectEVT(null); EventManager.TriggerEvent("CameraTrackSelected", trackevt); }
///<summary>Method called from the EventManager to log a new message</summary> private void AddMessageToLog(EVTData data_) { if (data_.logMessage == null) { return; } //Adding the new message to the correct array switch (data_.logMessage.messageLogType) { case LogMessageEVT.LogType.General: this.generalMessages.Insert(0, data_.logMessage.messageText); if (this.generalMessages.Count > this.numberOfMessages) { this.generalMessages.RemoveAt(this.numberOfMessages); } this.UpdateGeneralLog(); break; case LogMessageEVT.LogType.Combat: this.combatMessages.Insert(0, data_.logMessage.messageText); if (this.combatMessages.Count > this.numberOfMessages) { this.combatMessages.RemoveAt(this.numberOfMessages); } this.UpdateCombatLog(); break; default: break; } }
//Function called when the mouse cursor is over this object private void OnMouseOver() { //Does nothing if the player mouse input is disabled if (MouseData.isMouseDisabled) { return; } //If left-clicked this frame, dispatches a delegate event with this object's data if (Input.GetMouseButtonDown(0)) { EVTData clickData = new EVTData(); clickData.objectSelected = new ObjectSelectedEVT(this.gameObject); //If left shift is held, this object is added to the current selection if (Input.GetKey(KeyCode.LeftShift)) { EventManager.TriggerEvent("MultiObjectSelect", clickData); } //Otherwise, this is the only object currently selected else { EventManager.TriggerEvent("DisplayObjectSelected", clickData); } } //If right-clicked this frame, sets this object as the attack target of the current selection else if (Input.GetMouseButtonDown(1)) { EVTData clickData = new EVTData(); clickData.objectSelected = new ObjectSelectedEVT(this.gameObject); EventManager.TriggerEvent("AttackObjectSelected", clickData); } }
//Function inherited from MapLocation.cs that loads the Cursed Shrine UI when the player travels there public override void TravelToLocation() { EVTData logMessage = new EVTData(); logMessage.logMessage = new LogMessageEVT(LogMessageEVT.LogType.General, "Attempting to travel to " + this.locationName); EventManager.TriggerEvent(LogMessageEVT.eventNum, logMessage); }
//~~~~~~~~ UNFINISHED ~~~~~~~~~ //Function called from the EventManager.cs using the action2EVT delegate event private void MoveTest(EVTData data_) { if (!MouseData.objectSelected.Contains(this.gameObject)) { return; } }
/// <summary>Heals every character in the player's party a percentage of their max HP</summary> public void RestParty() { //Making sure the player has enough money to rest if (PartyGroup.globalReference.inventory.money < this.restGoldCost) { this.noMoneyAlertUI.SetActive(true); return; } PartyGroup.globalReference.inventory.money -= this.restGoldCost; HUDChallengeRampUpTimer.globalReference.AdvanceTimer(this.restTimeTaken); TimePanelUI.globalReference.AdvanceTime(8); //Looping through each of the characters in the player party for (int c = 0; c < PartyGroup.globalReference.charactersInParty.Count; c++) { if (PartyGroup.globalReference.charactersInParty[c] != null) { int healAmount = Mathf.RoundToInt(PartyGroup.globalReference.charactersInParty[c].charPhysState.maxHealth * this.restHealPercent); PartyGroup.globalReference.charactersInParty[c].charPhysState.HealCharacter(healAmount); //Logging a message to indicate that the character was successfully healed EVTData messageData = new EVTData(); messageData.logMessage = new LogMessageEVT(LogMessageEVT.LogType.General, PartyGroup.globalReference.charactersInParty[c].charName + " has rested and healed " + healAmount + " (" + this.restHealPercent + " of max HP)"); EventManager.TriggerEvent(LogMessageEVT.eventNum, messageData); } } }
//Function called externally to save player progress. Called from the pause menu in GamePlay scene, and CreateTileGrid.cs in Start public void SavePlayerProgress() { //Sending out an event to toggle the save game icon UI on EVTData startSaveData = new EVTData(); startSaveData.saveData = new SaveDataEVT(true); EventManager.TriggerEvent(SaveDataEVT.eventNum, startSaveData); //Making sure the save folder exists this.CheckSaveDirectory(GameData.globalReference.saveFolder); //Creating a new PlayerProgress class that we'll save PlayerProgress currentProgress = new PlayerProgress(GameData.globalReference, TileMapManager.globalReference, LevelUpManager.globalReference, CharacterManager.globalReference, QuestTracker.globalReference); //Serializing the current progress string jsonPlayerProgress = JsonUtility.ToJson(currentProgress, true); //Writing the JSON progress data to a new text file in the given folder's directory File.WriteAllText(Application.persistentDataPath + GameData.globalReference.saveFolder + "/" + this.defaultProgressFileName, jsonPlayerProgress); //Sending out an event to toggle the save game icon UI off EVTData endSaveData = new EVTData(); endSaveData.saveData = new SaveDataEVT(false); EventManager.TriggerEvent(SaveDataEVT.eventNum, endSaveData); }
//Private function called from the EventManager using our delegate. Triggers all UnityEvents private void EventTriggered(EVTData data_) { //Invokes all UnityEvents foreach (UnityEvent evt in this.eventsOnReceive) { evt.Invoke(); } }
//Function called when the DisplayObjectSelect event is triggered private void DisplayObjectSelect(EVTData data_) { //Checks to see if this script's display object was the one selected if (data_.objectSelected.objectSelected != this.displayObject) { return; } }
//Function used to update all of the sliders and text fields to the character's current values public void UpdateTextAndSliders(EVTData data_) { //Setting the name field to display the selected character's name this.nameText.text = this.selectedCharacter.firstName + "\n" + this.selectedCharacter.lastName; //Setting the sex field to display their sex this.sexText.text = "Sex: " + this.selectedCharacter.sex; //Setting the race field to display their race this.raceText.text = "Race: " + this.selectedCharacter.charRaceTypes.race; }
//Function called from the combatTransitionListener delegate from CombatTransitionEVT events private void CombatTransitioning(EVTData data_) { //Making sure the combat transition event data isn't null if (data_.combatTransition != null) { //Setting the isInCombat bool based on if combat is starting or ending this.isInCombat = data_.combatTransition.startingCombat; } }
//Called from the Event Manager when the sound settings have been changed private void SettingsChanged(EVTData data) { float emitterTypeVol = 1.0f; //Finds the volume of the emitter type based on what kind of sound it emits switch (this.soundEmitterType) { case SoundType.Dialogue: if (AudioSettings.globalReference.muteDialogue) { emitterTypeVol = 0; } else { emitterTypeVol = AudioSettings.globalReference.dialogueVolume; } break; case SoundType.Music: if (AudioSettings.globalReference.muteMusic) { emitterTypeVol = 0; } else { emitterTypeVol = AudioSettings.globalReference.musicVolume; } break; case SoundType.SFX: if (AudioSettings.globalReference.muteSoundEffects) { emitterTypeVol = 0; } else { emitterTypeVol = AudioSettings.globalReference.soundEffectVolume; } break; //Uses music by default default: if (AudioSettings.globalReference.muteMusic) { emitterTypeVol = 0; } else { emitterTypeVol = AudioSettings.globalReference.musicVolume; } break; } //Sets this owner's sound emitter volume based on the settings this.ownerAudio.volume = emitterTypeVol * this.defaultVol; }
/// <summary>Method called from InputCommand to heal a party member</summary> /// <param name="command_">The array of words that make up the command. Index 1 is required to be the character index. Index 2 is an optional amount to heal</param> private void HealPartyMember(string[] command_) { //Event to send a message to the log EVTData logEVT = new EVTData(); //If the party group doesn't exist due to not being in an active game, the heal fails if (PartyGroup.globalReference == null) { logEVT.logMessage = new LogMessageEVT(LogMessageEVT.LogType.General, "Cannot Heal Party Character: Player Party Does Not Exist"); EventManager.TriggerEvent(LogMessageEVT.eventNum, logEVT); return; } //Making sure the index given is actually an integer bool parseWorked = int.TryParse(command_[1], out int healID); //If the index isn't an integer, we output an error message if (!parseWorked) { logEVT.logMessage = new LogMessageEVT(LogMessageEVT.LogType.General, "Cannot Heal Party Character: Invalid Character Index " + command_[1]); EventManager.TriggerEvent(LogMessageEVT.eventNum, logEVT); return; } //If the index is an integer but is out of bounds of the party array, we output an error message if (healID < 0 || healID >= PartyGroup.globalReference.charactersInParty.Count) { logEVT.logMessage = new LogMessageEVT(LogMessageEVT.LogType.General, "Cannot Heal Party Character: Invalid Character Index " + command_[1]); EventManager.TriggerEvent(LogMessageEVT.eventNum, logEVT); return; } //If there's no character at the designated party index, we output an error message if (PartyGroup.globalReference.charactersInParty[healID] == null) { logEVT.logMessage = new LogMessageEVT(LogMessageEVT.LogType.General, "Cannot Heal Party Character: No Party Character At Index"); EventManager.TriggerEvent(LogMessageEVT.eventNum, logEVT); return; } //The default amount of health to give to the target character (full heal) int healAmount = 999999999; if (command_.Length > 2) { //Making sure the designated amount to heal given is actually an integer bool parse2Worked = int.TryParse(command_[2], out int newAmount); if (parse2Worked) { healAmount = newAmount; } } logEVT.logMessage = new LogMessageEVT(LogMessageEVT.LogType.General, "Heal Party Character: " + PartyGroup.globalReference.charactersInParty[healID].charName); EventManager.TriggerEvent(LogMessageEVT.eventNum, logEVT); PartyGroup.globalReference.charactersInParty[healID].charPhysState.HealCharacter(healAmount); }
//Function called from the changeTeamEVT delegate event. Changes this player's team private void ChangeTeam(EVTData data_) { //Does nothing if this isn't the player that's changing teams if (data_.playerChangeTeam.playerID != this.playerID) { return; } this.playerTeam = data_.playerChangeTeam.teamID; }
//Function called from the combatTransitionListener delegate from CombatTransitionEVT events private void CombatTransitioning(EVTData data_) { //Making sure the combat transition event data isn't null if (data_.combatTransition != null) { //Setting the isInCombat bool based on if combat is starting or ending this.hudObject.enabled = !data_.combatTransition.startingCombat; TimePanelUI.globalReference.SetTimePaused(data_.combatTransition.startingCombat); } }
/*Function called from the EventManager.cs using the moveToTargetEVT delegate event * Sets the target position for this ship to move to */ private void MoveToTarget(EVTData data_) { //Does nothing if this object is not selected if (!MouseData.objectSelected.Contains(gameObject)) { return; } this.movePos = new Vector3(data_.mapClick.clickCoords.x, 0, data_.mapClick.clickCoords.z); }
/* Function called from the EventManager.cs using the trackObjectEVT delegate event * Sets the object transform that this object will interpolate to, or clears it to stop interpolating */ private void SetObjectToTrack(EVTData data_) { if (data_.cameraTrackObject.objectToFollow != null) { this.objectToFollow = data_.cameraTrackObject.objectToFollow.transform; } else { this.objectToFollow = null; } }
//Function called externally whenever time advances to update the description public void UpdateDescriptionOnTimeAdvance(EVTData data_) { //If our current index is invalid or the description content is hidden, nothing happens if (this.displayedQuestPanelIndex < 0 || this.displayedQuestPanelIndex >= this.questPanels.Count || !this.descriptionContentTransform.gameObject.activeInHierarchy) { return; } //We update the quest description to show the change in time this.DisplayQuestDescription(this.displayedQuestPanelIndex); }
//Function called from the EventManager private void BeginTransition(EVTData data_) { //Using the image to block input this.fadeImage.raycastTarget = true; //Getting the transition settings from the event data this.transitionTime = data_.sceneTransition.transitionTime; this.newSceneName = data_.sceneTransition.newSceneName; this.currentTime = 0; this.blackScreenTime = data_.sceneTransition.stayOnBlackTime; //Setting the state to begin fading out this.tState = 1; }