using UnityEngine;
using UnityEngine.UI;
using W.o.N_Stats;
using System;
using System.Collections;
using UnityEngine.EventSystems;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
code
public class Player : MonoBehaviour
{
#region Stats Name And Player Info
// Property to set or get the player name
public string PlayerName
{
get { return PlayerPrefs.GetString("PlayerName", "Default Name"); }
set { PlayerPrefs.SetString("PlayerName", value); }
}
[Header("Level and Experience")]
public int PlayerLevel;
public int CurrentEXP;
public int ExpToLevelUp;
[Header("Health")]
public int currentHealth;
public int maxHealth;
[Header("Mana")]
public int currentMana;
public int maxMana;
[Header("Defense")]
public int currentDefense;
public int maxDefense;
[Header("Attack")]
public int currentAttack;
public int maxAttack;
[Header("Attack Speed")]
public float currentAttackSpeed;
public float maxAttackSpeed;
[Header("Critical")]
public int currentCritical;
public int maxCritical;
[Header("Life Steal")]
public float currentLifeSteal;
public float maxLifeSteal;
[Header("Range")]
public float currentRange;
public float maxRange;
[Header("Elemental Mastery")]
public float currentElementalMastery;
public float maxElementalMastery;
[Header("Cooldown")]
public float currentCooldown;
public float maxCooldown;
[Header("Knockback")]
public float currentKnockback;
public float maxKnockback;
[Header("Speed")]
public float currentSpeed;
public float maxSpeed;
[Header("Recovery")]
public float currentRecovery;
public float maxRecovery;
[Header("Evade")]
public float currentEvade;
public float maxEvade;
[Header("Fortune")]
public float currentFortune;
public float maxFortune;
[Header("Character and Stat Panel")]
public Character character;
public StatPanel statPanel;
public PlayerSkill playerSkill;
public Inventory inventory;
public EquipmentPanel equipmentPanel;
[Header("Hurt Effect")]
[SerializeField] private GameObject hurtParticlePrefab;
[SerializeField]
private PlayerDamageIndicator damageIndicatorScript; // Reference to the PlayerDamageIndicator script
public PlayerLevelUpText levelUpTextScript; // Reference to the PlayerLevelUpText script
#endregion
private float lastDamageTime = 0f; // Track the time of the last damage taken or mana used
private float lastRecoveryTime = 0f;
private bool hasEquippedItemRecently = false;
private float timeSinceEquippingItem = 0f;
private float equipItemRecoveryDelay = 30f;
[Header("Player Camera")]
public Camera playerCamera; // Assign the player's camera directly in the inspector
[Header("Button Assignment")]
public float attackRange = 2f;
public LayerMask mobsLayer; // Specify the layer for "Mobs"
[SerializeField] private bool displayGizmo = true; // Toggle to display Gizmo
// Event to notify UI that stats have changed
public Action OnStatsChanged { get; set; }
private void OnDrawGizmos()
{
if (displayGizmo)
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}
// Method to update the player's name
public void UpdatePlayerName(string newName)
{
PlayerName = newName;
}
#region Take Damage & Respawn
code
public void TakeDamage(int damage)
{
// Spawn the hurt particle effect if the prefab is assigned
if (hurtParticlePrefab != null)
{
GameObject hurtParticle = Instantiate(hurtParticlePrefab, transform.position, Quaternion.identity);
Destroy(hurtParticle, 0.45f); // Destroy the particle effect after 0.45 seconds
}
// Call the ShowDamageText method from PlayerDamageIndicator script and pass the damage value
if (damageIndicatorScript != null)
{
damageIndicatorScript.ShowDamageText(damage);
}
// Check if the player can evade
if (UnityEngine.Random.Range(0f, 100f) <= currentEvade)
{
Debug.Log($"{PlayerName} Evaded the Attack & Avoided {damage} Damage!");
}
else
{
// Calculate actual damage after considering defense
int actualDamage = Mathf.Max(0, damage - currentDefense);
// Damage defense first if there's any
if (currentDefense > 0)
{
int defenseDamage = Mathf.Max(0, damage - actualDamage);
currentDefense = Mathf.Max(0, currentDefense - damage);
// Log damage taken to defense if defense is greater than 0
if (defenseDamage > 0)
{
Debug.Log($"{PlayerName} Defense took {defenseDamage} damage!");
}
}
// If defense is reduced to 0, or no defense, damage health
if (currentDefense == 0)
{
int healthDamage = actualDamage;
currentHealth -= healthDamage;
// Log the health damage
Debug.Log($"{PlayerName} took {healthDamage} damage to health!");
// Check if health reaches 0
if (currentHealth <= 0)
{
Debug.Log($"{PlayerName} Died!");
// Respawn the player at the saved location and restore all stats to full
LoadPlayerData(PlayerName); // Respawn the player using saved data
RespawnPlayer();
}
}
}
// Update the last damage time to trigger recovery
lastDamageTime = Time.time;
}
private void RespawnPlayer()
{
// Restore all stats to full
SetCurrentStatsToMax(); // Reset current stats to their maximum values
// Teleport the player back to the saved location using the PlayerSaveLocation script
PlayerSaveLocation saveLocationScript = GetComponent<PlayerSaveLocation>();
if (saveLocationScript != null)
{
saveLocationScript.TeleportToSavedLocation();
}
}
#endregion
#region Start And Update
void Start()
{
// Construct the base directory path
code
SetStartingStats(); // Call this method to set starting stats
InitializeStats();
SetCurrentStatsToMax();
// Set the initial values for level and experience
PlayerLevel = 1;
CurrentEXP = 0;
ExpToLevelUp = 250;
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA", PlayerName);
// Check if the player's directory exists
if (Directory.Exists(baseDirectory))
{
// Construct the full file path for the player's data file
string filePath = Path.Combine(baseDirectory, $"{PlayerName}_Data.sav");
// Check if the player's data file exists
if (File.Exists(filePath))
{
// Load player data from file
LoadPlayerData(PlayerName);
}
}
}
private void Update()
{
// This Bellow When An Item Is Equipped It Will Update The Stats on Both The UI And The Player
UpdateMaxStats();
// Check if enough time has passed since the last damage or mana/defense depletion
if (!hasEquippedItemRecently && Time.time - lastDamageTime >= 30f)
{
// Increment current health, mana, and defense towards their maximum values over time
if (Time.time - lastRecoveryTime >= 5f) // Check if 5 seconds have passed since last recovery
{
// Increment stats by maxRecovery amount
currentHealth = Mathf.Min(maxHealth, currentHealth + Mathf.RoundToInt(maxRecovery));
currentMana = Mathf.Min(maxMana, currentMana + Mathf.RoundToInt(maxRecovery));
currentDefense = Mathf.Min(maxDefense, currentDefense + Mathf.RoundToInt(maxRecovery));
// Update the last recovery time
lastRecoveryTime = Time.time;
}
}
// Update the time since equipping an item
if (hasEquippedItemRecently)
{
timeSinceEquippingItem += Time.deltaTime;
if (timeSinceEquippingItem >= equipItemRecoveryDelay)
{
// Enough time has passed after equipping an item, reset the flag and trigger recovery
hasEquippedItemRecently = false;
lastDamageTime = Time.time;
}
}
}
#endregion
#region Level Up
public void LevelUp()
{
// Call the LevelUpText method from PlayerLevelUpText script
if (levelUpTextScript != null)
{
levelUpTextScript.ShowLevelUpText();
}
code
#region Save And Load System
code
public void SavePlayerData()
{
// Create a PlayerData object and populate it with current player state
PlayerData data = new PlayerData();
data.playerName = PlayerName;
data.playerLevel = PlayerLevel;
data.currentEXP = CurrentEXP;
data.expToLevelUp = ExpToLevelUp;
data.currentHealth = currentHealth;
data.maxHealth = maxHealth;
data.currentMana = currentMana;
data.maxMana = maxMana;
data.currentDefense = currentDefense;
data.maxDefense = maxDefense;
data.currentAttack = currentAttack;
data.maxAttack = maxAttack;
data.currentAttackSpeed = currentAttackSpeed;
data.maxAttackSpeed = maxAttackSpeed;
data.currentCritical = currentCritical;
data.maxCritical = maxCritical;
data.currentLifeSteal = currentLifeSteal;
data.maxLifeSteal = maxLifeSteal;
data.currentRange = currentRange;
data.maxRange = maxRange;
data.currentElementalMastery = currentElementalMastery;
data.maxElementalMastery = maxElementalMastery;
data.currentSpeed = currentSpeed;
data.maxSpeed = maxSpeed;
data.currentCooldown = currentCooldown;
data.maxCooldown = maxCooldown;
data.currentKnockback = currentKnockback;
data.maxKnockback = maxKnockback;
data.currentRecovery = currentRecovery;
data.maxRecovery = maxRecovery;
data.currentEvade = currentEvade;
data.maxEvade = maxEvade;
data.currentFortune = currentFortune;
data.maxFortune = maxFortune;
data.playerPosX = transform.position.x;
data.playerPosY = transform.position.y;
data.playerPosZ = transform.position.z;
// Adjusted file path
string saveDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA", PlayerName);
string fileName = $"{PlayerName}_Data.sav"; // Adjusted file name here
string savePath = Path.Combine(saveDirectory, fileName);
try
{
// Create directory if it doesn't exist
Directory.CreateDirectory(saveDirectory);
using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fileStream, data);
}
Debug.Log($"<color=#ADD8E6><b>Player data saved successfully</b></color> to: {savePath}");
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to save player data: {e.Message}</b></color>");
}
}
public void LoadPlayerData(string playerName)
{
// Construct the base directory path
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
code
#endregion
}
Assistant
This Unity script defines a Player class that manages various aspects of a player's stats, level progression, damage, recovery, and save/load functionality. Below are some key features and aspects of this script:
Key Features:
Player Info and Stats:
The player's name can be set or retrieved using PlayerPrefs.
Stats include health, mana, defense, attack, attack speed, critical chance, life steal, range, elemental mastery, cooldown, knockback, speed, recovery, evade, and fortune.
Uses Unity’s Header attribute to organize variables in the inspector.
Damage Handling:
Damage calculation takes into account the player's defense.
Evade mechanic lets the player avoid damage based on a random chance compared to the current evade stat.
Displays a visual effect and damage text when the player takes damage.
Respawns the player when health drops to zero using pre-saved data.
Leveling System:
Experience points (EXP) are gained and tracked.
Leveling up increases stat values and resets EXP.
Displays a level-up text effect using PlayerLevelUpText script.
Stat Management:
Automatically updates stats when items are equipped or in case of certain events (like level up).
Clamps current stats to their maximum values and handles adjustments based on conditions.
Provides methods for gaining experience and adding stats (e.g., from items or abilities).
Save and Load System:
Uses BinaryFormatter for saving/loading player data as a serialized file in the user's Documents folder.
Handles errors in saving/loading files and provides debugging output.
Player's stats and position are saved and restored.
Utilities & Others:
Gizmos for displaying attack range visualization in the Scene view.
Incorporates item equipment impact on stats with recovery delays.
Implements Coroutine functionality for use in the item system.
Considerations & Best Practices:
Performance & Readability: Be mindful that using a lot of public variables can clutter the inspector, consider using a more structured data approach like ScriptableObjects for storing base stats and player data.
User
using System;
[Serializable]
public class PlayerData
{
public string playerName;
code
public int playerLevel;
public int currentEXP;
public int expToLevelUp;
public int currentHealth;
public int maxHealth;
public int currentMana;
public int maxMana;
public int currentDefense;
public int maxDefense;
public int currentAttack;
public int maxAttack;
public float currentAttackSpeed;
public float maxAttackSpeed;
public int currentCritical;
public int maxCritical;
public float currentLifeSteal;
public float maxLifeSteal;
public float currentRange;
public float maxRange;
public float currentElementalMastery;
public float maxElementalMastery;
public float currentSpeed;
public float maxSpeed;
public float currentCooldown;
public float maxCooldown;
public float currentKnockback;
public float maxKnockback;
public float currentRecovery;
public float maxRecovery;
public float currentEvade;
public float maxEvade;
public float currentFortune;
public float maxFortune;
public float playerPosX;
public float playerPosY;
public float playerPosZ;
}
Assistant
The PlayerData class you provided serves as a data structure for storing a player's state. It is marked with the [Serializable] attribute, which allows instances of this class to be serialized and deserialized. This functionality is crucial for saving and loading player data to and from persistent storage. Here's a breakdown of what's included in this class:
Fields and their Purpose
Player Info:
playerName: Stores the name of the player.
Leveling and Experience:
playerLevel: The current level of the player.
currentEXP: The current accumulated experience points.
expToLevelUp: The experience points needed to level up.
Player Stats:
Health: currentHealth and maxHealth.
Mana: currentMana and maxMana.
Defense: currentDefense and maxDefense.
Attack: currentAttack and maxAttack.
Attack Speed: currentAttackSpeed and maxAttackSpeed.
Critical: currentCritical and maxCritical.
Life Steal: currentLifeSteal and maxLifeSteal.
Range: currentRange and maxRange.
Elemental Mastery: currentElementalMastery and maxElementalMastery.
Speed: currentSpeed and maxSpeed.
Cooldown: currentCooldown and maxCooldown.
Knockback: currentKnockback and maxKnockback.
Recovery: currentRecovery and maxRecovery.
Evade: currentEvade and maxEvade.
Fortune: currentFortune and maxFortune.
Player Position:
playerPosX, playerPosY, playerPosZ: Store the player's position coordinates in the world.
User
using UnityEngine;
using UnityEngine.UI;
using W.o.N_Stats;
public class Character : MonoBehaviour
{
[Header("Stats")]
public CharacterStat Health;
public CharacterStat Mana;
public CharacterStat Defence;
public CharacterStat Attack;
public CharacterStat AttackSpeed;
public CharacterStat Critical;
public CharacterStat LifeSteal;
public CharacterStat Range;
public CharacterStat ElementalMastery;
public CharacterStat Speed;
public CharacterStat Cooldown;
public CharacterStat Knockback;
public CharacterStat Recovery;
public CharacterStat Evade;
public CharacterStat Fortune;
code
Assistant
This Character class in Unity is designed to manage the character's attributes and interactions with various in-game systems such as inventory, equipment, and stat updates. Below, I will explain the key components and functionality of this script:
Key Components:
Stats Management:
The class holds various CharacterStat objects such as Health, Mana, Defense, etc. These stats can be dynamically updated based on different game mechanics like leveling up or equipping items.
Inventory and Equipment:
References to Inventory and EquipmentPanel are used to manage items in the player's inventory and equipped on the character.
Supports interaction with inventory slots, including equipping and using items through a drag-and-drop system.
User Interface Interactions:
The class interacts with UI elements to show item tooltips, enable dragging of items, and provide feedback to the player on actions like equipping or using an item.
Singleton Pattern:
Implements a singleton-like pattern using instance to ensure only one Character instance can be easily accessed at a time.
Event Handling:
Subscribes to various UI-related events such as right-click, drag, drop, etc., to define how items should be handled under different conditions.
Seed Selection:
Includes functionality to select and manage seed items, including visual feedback when a seed is selected.
Functions Explained:
Stat Functions:
UpdateStatValues: Called to refresh the stat values, which could involve updating UI elements to reflect changes.
LoadStatsFromData: Accepts a PlayerData object to sync the character's stats with saved data.
Inventory/Equipment Management:
Equip and Unequip: Handle the processes of equipping and unequipping items, ensuring that stats are updated and items are transferred correctly between inventory and equipment slots.
User
okay i have an issue with these 3 scritps would you mind helping me ?
can you ensure that when saving and loading equipment and player stats , that current stwats remain as current stats and max stats remain as max stats because i been having an issue where i leave the game and return , and my max stats on my sliders become my current values , meaning if i lave the game when im hurt , i have 300 current Health over 1000max health, for some reason when i load the game my max health becomes my current health . ruining all my players advancements and leaveups
dont tell me what is wrong just fix the code for me pelase.
Assistant
To address the issue where your max stats are being set to the current stats upon loading, we need to ensure that during the load process, the stats are correctly assigned to their respective "current" and "max" fields. Let's adjust your code to specifically address this concern.
Here’s a refined version of the save and load functionality based on the scripts you provided:
Adjustments
Ensure LoadPlayerData Sets Stats Correctly: Only set the max stats from the PlayerData object to the character and ensure that current stats are set from their specific fields (currentHealth, etc.).
Initialize Current and Max Stats Correctly During Load and Setup:
Ensure that during loading, max values from saved data are set to max stat fields and current values are correctly assigned to current stat fields.
Here's how you could adjust the loading code:
csharp
User
okay can you give me al lthe stats if you may
Assistant
Certainly! From the scripts you provided, the stats in your game seem to be divided into current and max values for many attributes. Here’s a consolidated list of the stats for both current and max states:
Character Stats:
Health:
currentHealth
maxHealth
Mana:
currentMana
maxMana
Defense:
currentDefense
maxDefense
Attack:
currentAttack
maxAttack
Attack Speed:
currentAttackSpeed
maxAttackSpeed
Critical:
currentCritical
maxCritical
Life Steal:
currentLifeSteal
maxLifeSteal
Range:
currentRange
maxRange
Elemental Mastery:
currentElementalMastery
maxElementalMastery
Speed:
currentSpeed
maxSpeed
Cooldown:
currentCooldown
maxCooldown
Knockback:
currentKnockback
maxKnockback
Recovery:
currentRecovery
maxRecovery
Evade:
currentEvade
maxEvade
Fortune:
currentFortune
maxFortune
General Handling Tips:
Saving/Loading: Ensure that both current and max stats are correctly saved to and loaded from your data storage. current values should reflect the temporary state at the moment of saving, and max values should reflect the character's potential upper limits based on level, equipment, and other permanent bonuses.
Stat Updates: When stats are updated, particularly during game events such as leveling up or equipping items, ensure updates respect the distinction between current states (temporary state) and maximum stats (limits or potential).
By managing these stats effectively, both through code and player interface, you can ensure that your game behaves predictably and provides a smooth experience for the player.
User
no give me al lthis with all the stats
public class Player : MonoBehaviour
{
// Other fields and methods...
code
public void LoadPlayerData(string playerName)
{
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
if (Directory.Exists(playerDirectory))
{
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
if (File.Exists(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = (PlayerData)formatter.Deserialize(fileStream);
// Ensure to set both current and max stats
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
// Load current and max stats separately
currentHealth = data.currentHealth;
maxHealth = data.maxHealth;
currentMana = data.currentMana;
maxMana = data.maxMana;
currentDefense = data.currentDefense;
maxDefense = data.maxDefense;
// Set other current stats and max stats similarly...
// Assuming LoadStatsFromData method sets max stats for character
character.LoadStatsFromData(data);
// Set the correct current stats after loading
SetCurrentStatsToLoadedValues();
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
Debug.Log("<color=#00FF00><b>Loaded PlayerData</b></color>");
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
else
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
}
}
}
private void SetCurrentStatsToLoadedValues()
{
// Ensure current values are being used appropriately post load
currentHealth = Mathf.Min(currentHealth, maxHealth);
currentMana = Mathf.Min(currentMana, maxMana);
currentDefense = Mathf.Min(currentDefense, maxDefense);
// Continue for other stats...
}
Assistant
Certainly! I will integrate all the stats listed in the previous breakdown into the LoadPlayerData method and the SetCurrentStatsToLoadedValues method. This ensures that each stat's current and max values are loaded correctly, and current values do not exceed their associated max values.
Here's how you can modify your code to include all the specified stats:
csharp
User
#region Save And Load System
code
public void SavePlayerData()
{
// Create a PlayerData object and populate it with current player state
PlayerData data = new PlayerData();
data.playerName = PlayerName;
data.playerLevel = PlayerLevel;
data.currentEXP = CurrentEXP;
data.expToLevelUp = ExpToLevelUp;
data.currentHealth = currentHealth;
data.maxHealth = maxHealth;
data.currentMana = currentMana;
data.maxMana = maxMana;
data.currentDefense = currentDefense;
data.maxDefense = maxDefense;
data.currentAttack = currentAttack;
data.maxAttack = maxAttack;
data.currentAttackSpeed = currentAttackSpeed;
data.maxAttackSpeed = maxAttackSpeed;
data.currentCritical = currentCritical;
data.maxCritical = maxCritical;
data.currentLifeSteal = currentLifeSteal;
data.maxLifeSteal = maxLifeSteal;
data.currentRange = currentRange;
data.maxRange = maxRange;
data.currentElementalMastery = currentElementalMastery;
data.maxElementalMastery = maxElementalMastery;
data.currentSpeed = currentSpeed;
data.maxSpeed = maxSpeed;
data.currentCooldown = currentCooldown;
data.maxCooldown = maxCooldown;
data.currentKnockback = currentKnockback;
data.maxKnockback = maxKnockback;
data.currentRecovery = currentRecovery;
data.maxRecovery = maxRecovery;
data.currentEvade = currentEvade;
data.maxEvade = maxEvade;
data.currentFortune = currentFortune;
data.maxFortune = maxFortune;
data.playerPosX = transform.position.x;
data.playerPosY = transform.position.y;
data.playerPosZ = transform.position.z;
// Adjusted file path
string saveDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA", PlayerName);
string fileName = $"{PlayerName}_Data.sav"; // Adjusted file name here
string savePath = Path.Combine(saveDirectory, fileName);
try
{
// Create directory if it doesn't exist
Directory.CreateDirectory(saveDirectory);
using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fileStream, data);
}
Debug.Log($"<color=#ADD8E6><b>Player data saved successfully</b></color> to: {savePath}");
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to save player data: {e.Message}</b></color>");
}
}
Assistant
To address the issue where the max stats are not correctly restored upon loading the game, let's make sure that the save and load methods handle current and max values separately without mixing them up. The key point is to ensure that when saving data, you save both the current and max values, and when loading, you restore them exactly where they belong.
Here's how you can adjust your code to correctly manage this:
Code Adjustments
csharp
User
okay that is not workign when i load the game turns current health to max health and max health to current health makes no sence
i need for both current health and max health to load properly meaning current health = max health and max health = max health when loading
code
Assistant
To address the issue where current and max stats, particularly health, are not loading correctly, we can ensure that the loading function properly assigns these values and that there is no unintended operation resetting or affecting these stats post-load.
Let’s review and correct the relevant methods in your script to ensure that the loading functionality works as intended:
Corrective Measures:
Clear Separation in Load and Application: Ensure that the stats are loaded from the data file into distinct current and max fields and that these fields are properly utilized in other parts of your code.
Post-Load Processing Consideration: Ensure nothing in your existing code overrides or incorrectly adjusts the loaded stats, especially in the Start, SetStartingStats, InitializeStats, and similar methods.
Here’s the updated section for saving and loading stats:
csharp
User
does loading ensure this occurs
using UnityEngine;
using TMPro;
using UnityEngine.UI;
public class PlayerUI : MonoBehaviour
{
public TextMeshProUGUI playerNameText;
public TextMeshProUGUI playerLevelText;
public TextMeshProUGUI healthValueText;
public TextMeshProUGUI manaValueText;
public TextMeshProUGUI defenceValueText;
public TextMeshProUGUI expValueText;
The PlayerUI script you provided is responsible for updating the UI elements such as text and sliders to reflect the player's current stats. Let's analyze how it ensures the UI reflects the player's stats correctly when the game is loaded:
How the UI Updates:
Stat Display:
Text fields and sliders show the player's current and max stats for health, mana, defense, and experience.
The start method subscribes to the OnStatsChanged event to update the UI whenever the stats change.
Continuous Update:
The Update method in Unity runs every frame, ensuring that changes in the player's stats are captured and reflected in the UI through continuous updates. This mechanism helps in syncing UI with player stats dynamically, which includes changes arising from loading saved data.
Event-Driven UI Updates:
The UpdateUI method is called in two places: during each frame in the Update method and when OnStatsChanged is triggered. This ensures that even without regular frame-based updates, the UI would update when stats change due to gameplay events like receiving damage or equipping an item.
Ensuring Proper UI Reflection Upon Loading:
Loading Connection:
When LoadPlayerData is executed to restore stats, ensure it triggers OnStatsChanged after the loading is complete. This will update the UI with the loaded stats using the event-driven approach.
Potential Improvement:
Consider integrating an explicit call to UpdateUI after loading data to avoid relying solely on the event mechanism, especially if there are any reasons the event might not trigger immediately or the designer prefers certainty.
Example alteration in LoadPlayerData to trigger UI update:
csharp
public void LoadPlayerData(string playerName)
{
// Original data loading logic...
// Trigger UI update after loading
if (OnStatsChanged != null)
{
OnStatsChanged.Invoke();
playerUI.UpdateUI(); // Ensure UI is updated with loaded stats
}
}
User
give me full LoadPlayerData(string playerName)
Assistant
To ensure that the LoadPlayerData(string playerName) method works correctly and updates the UI as expected, we need to verify that the player stats are accurately loaded from saved data and that the UI updates promptly reflect these values. Here is the full implementation of the LoadPlayerData method along with triggering the OnStatsChanged event to make sure the UI updates accordingly after loading. Additionally, I'll include a call to update the UI directly for extra assurance.
csharp
User
using UnityEngine;
using UnityEngine.UI;
using W.o.N_Stats;
using System;
using System.Collections;
using UnityEngine.EventSystems;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
code
Assistant
To address the issue of loading the correct stats such that the player's max values are set correctly and the current values are updated accordingly, let’s ensure the LoadPlayerData method works as intended to use the loaded data properly. Here, I’ll provide an improved version of this method while addressing the relationship between Player and Character, assuming Character has base values that influence potential max values for the player.
Important Concepts
Separation of Concerns: Distinguish between character base stats (like templates or upgrades from levels) and player-specific values that reflect current state and progression (like damage or temporary boosts).
Consistent Loading: Ensure that loading data resets state to what's saved, specifically loading max values directly from the saved data unless other game logic requires adjustments (e.g., effects, debuffs).
Here is how the corrected LoadPlayerData method could look:
csharp
Not yet included in a published release.
PlayerLevel++;
CurrentEXP -= ExpToLevelUp;
ExpToLevelUp *= 2;
// Update character stats
character.Health.BaseValue += 5 * PlayerLevel;
character.Mana.BaseValue += 2 * PlayerLevel;
character.Defence.BaseValue += 1 * PlayerLevel;
character.Attack.BaseValue += 1 * PlayerLevel;
character.AttackSpeed.BaseValue += 0.008f * PlayerLevel;
character.Critical.BaseValue += 0.05F * PlayerLevel;
character.LifeSteal.BaseValue += 0.5f * PlayerLevel;
character.Range.BaseValue += 0.015f * PlayerLevel;
character.ElementalMastery.BaseValue += 0.13f * PlayerLevel;
character.Cooldown.BaseValue += 0.1f * PlayerLevel;
character.Knockback.BaseValue += 0.025f * PlayerLevel;
character.Speed.BaseValue += 0.005f * PlayerLevel;
character.Recovery.BaseValue += 0.5f * PlayerLevel;
character.Evade.BaseValue += 0.01f * PlayerLevel;
character.Fortune.BaseValue += 0.015f * PlayerLevel;
// Update stat values
character.UpdateStatValues();
// Update max stats
UpdateMaxStats();
// Set current stats to max
SetCurrentStatsToMax();
// Show updated stats on UI
statPanel.SetStats(character.Health, character.Mana, character.Defence, character.Attack , character.AttackSpeed, character.Critical, character.LifeSteal, character.Range, character.ElementalMastery, character.Speed, character.Cooldown, character.Knockback, character.Recovery, character.Evade, character.Fortune);
}
#endregion
private void SetStartingStats()
{
// Set starting stats for the player based on character stats
currentHealth = (int)character.Health.Value;
maxHealth = (int)character.Health.Value;
currentMana = (int)character.Mana.Value;
maxMana = (int)character.Mana.Value;
currentDefense = (int)character.Defence.Value;
maxDefense = (int)character.Defence.Value;
currentAttack = (int)character.Attack.Value;
maxAttack = (int)character.Attack.Value;
currentAttackSpeed = character.AttackSpeed.Value;
maxAttackSpeed = character.AttackSpeed.Value;
currentCritical = (int)character.Critical.Value;
maxCritical = (int)character.Critical.Value;
currentLifeSteal = character.LifeSteal.Value;
maxLifeSteal = character.LifeSteal.Value;
currentRange = character.Range.Value;
maxRange = character.Range.Value;
currentElementalMastery = character.ElementalMastery.Value;
maxElementalMastery = character.ElementalMastery.Value;
currentSpeed = character.Speed.Value;
maxSpeed = character.Speed.Value;
currentCooldown = character.Cooldown.Value;
maxCooldown = character.Cooldown.Value;
currentKnockback = character.Knockback.Value;
maxKnockback = character.Knockback.Value;
currentRecovery = character.Recovery.Value;
maxRecovery = character.Recovery.Value;
currentEvade = character.Evade.Value;
maxEvade = character.Evade.Value;
currentFortune = character.Fortune.Value;
maxFortune = character.Fortune.Value;
// Call UpdateStatValues to apply the changes
character.UpdateStatValues();
// Update max and current stats
UpdateMaxStats();
SetCurrentStatsToMax();
}
// Update the maximum stats of the character
public void UpdateMaxStats()
{
// Update max stats for the player based on character stats
maxHealth = (int)character.Health.Value;
maxMana = (int)character.Mana.Value;
maxDefense = (int)character.Defence.Value;
maxAttack = (int)character.Attack.Value;
maxAttackSpeed = character.AttackSpeed.Value;
maxCritical = (int)character.Critical.Value;
maxLifeSteal = character.LifeSteal.Value;
maxRange = character.Range.Value;
maxElementalMastery = character.ElementalMastery.Value;
maxSpeed = character.Speed.Value;
maxCooldown = character.Cooldown.Value;
maxKnockback = character.Knockback.Value;
maxRecovery = character.Recovery.Value;
maxEvade = character.Evade.Value;
maxFortune = character.Fortune.Value;
}
// Check if any current stats have changed due to equipping items
public void CurrentStatsChange()
{
// Mark that an item has been equipped recently
hasEquippedItemRecently = true;
timeSinceEquippingItem = 0f;
}
public void InitializeStats()
{
// Update max stats
UpdateMaxStats();
// Initialize current stats
maxHealth = Mathf.RoundToInt(character.Health.Value);
currentHealth = maxHealth;
maxMana = Mathf.RoundToInt(character.Mana.Value);
currentMana = maxMana;
maxDefense = Mathf.RoundToInt(character.Defence.Value);
currentDefense = maxDefense;
maxAttack = Mathf.RoundToInt(character.Attack.Value);
currentAttack = maxAttack;
maxAttackSpeed = character.AttackSpeed.Value;
currentAttackSpeed = maxAttackSpeed;
maxCritical = Mathf.RoundToInt(character.Critical.Value);
currentCritical = maxCritical;
maxLifeSteal = Mathf.RoundToInt(character.LifeSteal.Value);
currentLifeSteal = maxLifeSteal;
maxRange = Mathf.RoundToInt(character.Range.Value);
currentRange = maxRange;
maxElementalMastery = Mathf.RoundToInt(character.ElementalMastery.Value);
currentElementalMastery = maxElementalMastery;
maxSpeed = Mathf.RoundToInt(character.Speed.Value);
currentSpeed = maxSpeed;
maxCooldown = character.Cooldown.Value;
currentCooldown = maxCooldown;
maxKnockback = Mathf.RoundToInt(character.Knockback.Value);
currentKnockback = maxKnockback;
maxRecovery = character.Recovery.Value;
currentRecovery = maxRecovery;
maxEvade = character.Evade.Value;
currentEvade = maxEvade;
maxFortune = Mathf.RoundToInt(character.Fortune.Value);
currentFortune = maxFortune;
// Replace UpdateCurrentStats with the appropriate method
// (e.g., SetCurrentStatsToMax or any other method that updates your current stats)
SetCurrentStatsToMax();
}
public void SetCurrentStatsToMax()
{
currentHealth = maxHealth;
currentMana = maxMana;
currentDefense = maxDefense;
currentAttack = maxAttack;
currentAttackSpeed = maxAttackSpeed;
currentCritical = maxCritical;
currentLifeSteal = maxLifeSteal;
currentRange = maxRange;
currentElementalMastery = maxElementalMastery;
currentCooldown = maxCooldown;
currentKnockback = maxKnockback;
currentSpeed = maxSpeed;
currentRecovery = maxRecovery;
currentEvade = maxEvade;
currentFortune = maxFortune;
// Reset the last recovery time to prevent immediate recovery
lastRecoveryTime = Time.time;
}
public void AdjustStatsIfNeeded()
{
// Health
int newMaxHealth = Mathf.RoundToInt(character.Health.Value);
if (newMaxHealth < currentHealth)
{
currentHealth = newMaxHealth;
}
// Mana
int newMaxMana = Mathf.RoundToInt(character.Mana.Value);
if (newMaxMana < currentMana)
{
currentMana = newMaxMana;
}
// Defense
int newMaxDefense = Mathf.RoundToInt(character.Defence.Value);
if (newMaxDefense < currentDefense)
{
currentDefense = newMaxDefense;
}
// Attack
int newMaxAttack = Mathf.RoundToInt(character.Attack.Value);
if (newMaxAttack < currentAttack)
{
currentAttack = newMaxAttack;
}
// Attack Speed
float newMaxAttackSpeed = character.AttackSpeed.Value;
if (newMaxAttackSpeed < currentAttackSpeed)
{
currentAttackSpeed = newMaxAttackSpeed;
}
// Critical
int newMaxCritical = Mathf.RoundToInt(character.Critical.Value);
if (newMaxCritical < currentCritical)
{
currentCritical = newMaxCritical;
}
// LifeSteal
int newMaxLifeSteal = Mathf.RoundToInt(character.LifeSteal.Value);
if (newMaxLifeSteal < currentLifeSteal)
{
currentLifeSteal = newMaxLifeSteal;
}
// Range
int newMaxRange = Mathf.RoundToInt(character.Range.Value);
if (newMaxRange < currentRange)
{
currentRange = newMaxRange;
}
// ElementalMastery
int newMaxElementalMastery = Mathf.RoundToInt(character.ElementalMastery.Value);
if (newMaxElementalMastery < currentElementalMastery)
{
currentElementalMastery = newMaxElementalMastery;
}
// Speed
float newMaxSpeed = character.Speed.Value;
if (newMaxSpeed < currentSpeed)
{
currentSpeed = newMaxSpeed;
}
// Cooldown
float newMaxCooldown = character.Cooldown.Value;
if (newMaxCooldown < currentCooldown)
{
currentCooldown = newMaxCooldown;
}
// Knockback
int newMaxKnockback = Mathf.RoundToInt(character.Knockback.Value);
if (newMaxKnockback < currentKnockback)
{
currentKnockback = newMaxKnockback;
}
// Recovery
float newMaxRecovery = character.Recovery.Value;
if (newMaxRecovery < currentRecovery)
{
currentRecovery = newMaxRecovery;
}
// Evade
float newMaxEvade = character.Evade.Value;
if (newMaxEvade < currentEvade)
{
currentEvade = newMaxEvade;
}
// Fortune
int newMaxFortune = Mathf.RoundToInt(character.Fortune.Value);
if (newMaxFortune < currentFortune)
{
currentFortune = newMaxFortune;
}
CurrentStatsChange();
}
public void IncreaseExperience(int amount)
{
CurrentEXP += amount;
while (CurrentEXP >= ExpToLevelUp)
{
LevelUp();
}
}
public void AddStats(int healthToAdd, int defenseToAdd, int manaToAdd)
{
// Check if adding health would exceed the maximum
if (currentHealth < maxHealth)
{
// Calculate the new health after adding
int newHealth = currentHealth + healthToAdd;
// Ensure the new health doesn't exceed the maximum
newHealth = Mathf.Clamp(newHealth, 0, maxHealth);
// If the new health is different from the current health, apply the change
if (newHealth != currentHealth)
{
currentHealth = newHealth;
CurrentStatsChange(); // Notify stats change if needed
}
}
// Check if adding defense would exceed the maximum
if (currentDefense < maxDefense)
{
// Calculate the new defense after adding
int newDefense = currentDefense + defenseToAdd;
// Ensure the new defense doesn't exceed the maximum
newDefense = Mathf.Clamp(newDefense, 0, maxDefense);
// If the new defense is different from the current defense, apply the change
if (newDefense != currentDefense)
{
currentDefense = newDefense;
CurrentStatsChange(); // Notify stats change if needed
}
}
// Check if adding mana would exceed the maximum
if (currentMana < maxMana)
{
// Calculate the new mana after adding
int newMana = currentMana + manaToAdd;
// Ensure the new mana doesn't exceed the maximum
newMana = Mathf.Clamp(newMana, 0, maxMana);
// If the new mana is different from the current mana, apply the change
if (newMana != currentMana)
{
currentMana = newMana;
CurrentStatsChange(); // Notify stats change if needed
}
}
}
// This allows the UsableItem to start coroutines on the player
public new Coroutine StartCoroutine(IEnumerator routine)
{
return base.StartCoroutine(routine);
}
// Check if the base directory exists
if (!Directory.Exists(baseDirectory))
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
return;
}
// Append the player's folder based on PlayerName
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
// Ensure the player's directory exists
if (!Directory.Exists(playerDirectory))
{
Debug.LogWarning($"<color=red><b>No saved data found for player: {PlayerName}</b></color>");
return;
}
// Construct the full file path
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
// Check if the file exists
if (File.Exists(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = formatter.Deserialize(fileStream) as PlayerData;
// Assign loaded data back to the player (optional, depends on your game's logic)
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
currentHealth = data.currentHealth;
maxHealth = data.maxHealth;
currentMana = data.currentMana;
maxMana = data.maxMana;
currentDefense = data.currentDefense;
maxDefense = data.maxDefense;
currentAttack = data.currentAttack;
maxAttack = data.maxAttack;
currentAttackSpeed = data.currentAttackSpeed;
maxAttackSpeed = data.maxAttackSpeed;
currentCritical = data.currentCritical;
maxCritical = data.maxCritical;
currentLifeSteal = data.currentLifeSteal;
maxLifeSteal = data.maxLifeSteal;
currentRange = data.currentRange;
maxRange = data.maxRange;
currentElementalMastery = data.currentElementalMastery;
maxElementalMastery = data.maxElementalMastery;
currentSpeed = data.currentSpeed;
maxSpeed = data.maxSpeed;
currentCooldown = data.currentCooldown;
maxCooldown = data.maxCooldown;
currentKnockback = data.currentKnockback;
maxKnockback = data.maxKnockback;
currentRecovery = data.currentRecovery;
maxRecovery = data.maxRecovery;
currentEvade = data.currentEvade;
maxEvade = data.maxEvade;
currentFortune = data.currentFortune;
maxFortune = data.maxFortune;
// Assuming 'character' is an instance of the Character class
character.LoadStatsFromData(data);
playerSkill.LoadSkillData(PlayerName);
// Position (example)
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
Debug.Log($"<color=#00FF00><b>Loaded PlayerData</b></color>");
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
else
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
}
}
Security: PlayerPrefs is not secure for storing sensitive data. Try to encrypt sensitive data or use a more secure system.
Separation of Concerns: Stats and character state might be better handled within their dedicated classes or systems (like ScriptableObjects, MVC structures, etc.) to make code more modular.
Save System Robustness: Consider using a more modern serialization library if you need more robust features, as BinaryFormatter is not supported in certain environments and versions of Unity after .NET 5.
Data Consistency: Ensure to update both current and max stats across different actions (e.g., leveling up, item equips).
By following these guidelines and augmentations, you can maintain the code's efficiency, readability, and extensibility.
Usage
Serialization: When saving player data, an instance of this PlayerData class will be created and filled with the current state of the player. This instance is then serialized and written to a file.
Deserialization: When loading player data, the file is deserialized back into an instance of PlayerData, and the stored values are used to restore the player's state.
Considerations
Versioning: If you plan to modify the structure of PlayerData over time, consider adding versioning to your save files. This helps manage changes to file structure smoothly.
Data Integrity: When dealing with floating-point numbers for position and other stats, be cautious of precision issues, especially if accuracy is paramount.
Security: If the data needs to be secure or tamper-proof, consider encrypting the serialized data.
By using this structured data model, extending and managing player-related data becomes more straightforward, and you ensure a clean separation between game logic and data storage.
public int maxHealth;
public int maxMana;
public int maxDefense;
public int maxAttack;
public float maxAttackSpeed;
public int maxCritical;
public float maxLifeSteal;
public float maxRange;
public float maxElementalMastery;
public float maxSpeed;
public float maxCooldown;
public float maxKnockback;
public float maxRecovery;
public float maxEvade;
public float maxFortune;
[Header("Public")]
public Inventory Inventory;
public EquipmentPanel EquipmentPanel;
public Player player; // Reference to the Player script
private WeaponTypeDetector weaponTypeDetector;
[Header("Selected Seed")]
public SeedItem selectedSeed; // Reference to the selected seed item
public Color normalColor = Color.white;
public Color selectedColor = new Color(0.5f, 0.5f, 0.5f, 1f);
private static Character instance; // Reference to the character instance
[Header("Serialize Field")]
[SerializeField] CraftingWindow craftingWindow;
[SerializeField] StatPanel statPanel;
[SerializeField] ItemTooltip itemTooltip;
[SerializeField] Image draggableItem;
[SerializeField] DropItemArea dropItemArea;
[SerializeField] QuestionDialog reallyDropItemDialog;
private BaseItemSlot dragItemSlot;
private void OnValidate()
{
if (itemTooltip == null)
itemTooltip = FindObjectOfType<ItemTooltip>();
}
public void Awake()
{
statPanel.SetStats(Health, Mana, Defence, Attack, AttackSpeed, Critical, LifeSteal, Range, ElementalMastery, Speed, Cooldown, Knockback, Recovery, Evade, Fortune);
instance = this; // Assign the current instance to the static variable
statPanel.UpdateStatValues();
// Get the WeaponTypeDetector component
weaponTypeDetector = GetComponent<WeaponTypeDetector>();
// Setup Events:
// Right Click
Inventory.OnRightClickEvent += InventoryRightClick;
EquipmentPanel.OnRightClickEvent += EquipmentPanelRightClick;
// Pointer Enter
Inventory.OnPointerEnterEvent += ShowTooltip;
EquipmentPanel.OnPointerEnterEvent += ShowTooltip;
craftingWindow.OnPointerEnterEvent += ShowTooltip;
// Pointer Exit
Inventory.OnPointerExitEvent += HideTooltip;
EquipmentPanel.OnPointerExitEvent += HideTooltip;
craftingWindow.OnPointerExitEvent += HideTooltip;
// Begin Drag
Inventory.OnBeginDragEvent += BeginDrag;
EquipmentPanel.OnBeginDragEvent += BeginDrag;
// End Drag
Inventory.OnEndDragEvent += EndDrag;
EquipmentPanel.OnEndDragEvent += EndDrag;
// Drag
Inventory.OnDragEvent += Drag;
EquipmentPanel.OnDragEvent += Drag;
// Drop
Inventory.OnDropEvent += Drop;
EquipmentPanel.OnDropEvent += Drop;
dropItemArea.OnDropEvent += DropItemOutsideUI;
}
public static Character GetInstance()
{
if (instance == null)
{
instance = FindObjectOfType<Character>(); // Find the Character instance in the scene
}
return instance;
}
private void Update()
{
// Change the following line to continuously update stats in real-time
UpdateStatValues();
}
private void InventoryRightClick(BaseItemSlot itemSlot)
{
// Deselect the currently selected seed if the clicked item is not a seed item
if (!(itemSlot.Item is SeedItem))
{
DeselectSeed();
}
// Handle the action for the clicked item
if (itemSlot.Item is EquippableItem)
{
Equip((EquippableItem)itemSlot.Item);
}
else if (itemSlot.Item is UsableItem)
{
// Use the Usable Item
UsableItem usableItem = (UsableItem)itemSlot.Item;
usableItem.Use(player); // Assuming 'player' is a reference to the Player script
Inventory.RemoveItem(usableItem); // Remove the used item from the inventory
}
else if (itemSlot.Item is SeedItem)
{
SeedItem seedItem = (SeedItem)itemSlot.Item;
// If the clicked seed is the same as the currently selected seed, deselect it
if (selectedSeed == seedItem)
{
DeselectSeed();
}
else // If the clicked seed is different from the currently selected one, select it
{
// Check if there's a previously selected seed, and deselect it
if (selectedSeed != null)
{
DeselectSeed();
}
selectedSeed = seedItem;
Debug.Log("Selected seed: " + selectedSeed.name);
UpdateSeedTintColors();
}
}
UpdateMax();
AdjustStatsIfNeeded();
}
private void DeselectSeed()
{
if (selectedSeed != null)
{
Debug.Log("Deselected seed: " + selectedSeed.name);
selectedSeed = null;
UpdateSeedTintColors();
}
}
private void UpdateSeedTintColors()
{
// Update tint colors of seed items based on selection state
foreach (BaseItemSlot itemSlot in Inventory.ItemSlots)
{
if (itemSlot.Item is SeedItem seedItem)
{
Image seedImage = itemSlot.GetComponent<Image>();
if (seedItem == selectedSeed)
{
seedImage.color = selectedColor;
}
else
{
seedImage.color = normalColor;
}
}
}
}
private void EquipmentPanelRightClick(BaseItemSlot itemSlot)
{
if (itemSlot.Item is EquippableItem)
{
Unequip((EquippableItem)itemSlot.Item);
}
UpdateMax();
}
private void ShowTooltip(BaseItemSlot itemSlot)
{
if (itemSlot.Item != null)
{
itemTooltip.ShowTooltip(itemSlot.Item);
}
}
private void HideTooltip(BaseItemSlot itemSlot)
{
if (itemTooltip.gameObject.activeSelf)
{
itemTooltip.HideTooltip();
}
}
private void BeginDrag(BaseItemSlot itemSlot)
{
if (itemSlot.Item != null && !(itemSlot is EquipmentSlot))
{
dragItemSlot = itemSlot;
draggableItem.sprite = itemSlot.Item.Icon;
draggableItem.transform.position = Input.mousePosition;
draggableItem.gameObject.SetActive(true);
}
}
private void Drag(BaseItemSlot itemSlot)
{
if (dragItemSlot != null)
{
draggableItem.transform.position = Input.mousePosition;
}
}
private void EndDrag(BaseItemSlot itemSlot)
{
dragItemSlot = null;
draggableItem.gameObject.SetActive(false);
}
private void Drop(BaseItemSlot dropItemSlot)
{
if (dragItemSlot == null) return;
code
// Case 1: Prevent dropping equippable items into equipment slots if the item is already equipped
if (dragItemSlot.Item is EquippableItem && dropItemSlot is EquipmentSlot)
{
EndDrag(null);
return;
}
// Case 2: Try to stack the item if dropItemSlot can accept stacks
if (dropItemSlot.CanAddStack(dragItemSlot.Item))
{
AddStacks(dropItemSlot);
}
// Case 3: Swap items if both slots can receive each other's items
else if (dropItemSlot.CanReceiveItem(dragItemSlot.Item) && dragItemSlot.CanReceiveItem(dropItemSlot.Item))
{
SwapItems(dropItemSlot, dragItemSlot);
}
// Case 4: Move item to dropItemSlot if it’s a valid drop
else if (dropItemSlot.CanReceiveItem(dragItemSlot.Item))
{
MoveItemToSlot(dropItemSlot, dragItemSlot);
RemoveItemFromSlot(dragItemSlot);
}
EndDrag(null);
private void AddStacks(BaseItemSlot dropItemSlot)
{
int numAddableStacks = dropItemSlot.Item.MaximumStacks - dropItemSlot.Amount;
int stacksToAdd = Mathf.Min(numAddableStacks, dragItemSlot.Amount);
dropItemSlot.Amount += stacksToAdd;
dragItemSlot.Amount -= stacksToAdd;
}
private void SwapItems(BaseItemSlot dropItemSlot, BaseItemSlot originalSlot)
{
Item draggedItem = originalSlot.Item;
int draggedItemAmount = originalSlot.Amount;
originalSlot.Item = dropItemSlot.Item;
originalSlot.Amount = dropItemSlot.Amount;
dropItemSlot.Item = draggedItem;
dropItemSlot.Amount = draggedItemAmount;
if (originalSlot is EquipmentSlot)
{
((EquippableItem)originalSlot.Item)?.Equip(this);
}
if (dropItemSlot is EquipmentSlot)
{
((EquippableItem)dropItemSlot.Item)?.Equip(this);
}
statPanel.UpdateStatValues();
}
private void DropItemOutsideUI()
{
if (dragItemSlot == null) return;
code
if (dragItemSlot.Item != null)
{
// Check if the dialog should be shown or bypassed
if (reallyDropItemDialog.ShouldAskAgain())
{
// Show the confirmation dialog
reallyDropItemDialog.Show();
BaseItemSlot slot = dragItemSlot;
reallyDropItemDialog.OnYesEvent += () => DestroyItemInSlot(slot);
}
else
{
// Directly destroy the item if the user opted not to be asked again
DestroyItemInSlot(dragItemSlot);
}
}
}
code
private void DestroyItemInSlot(BaseItemSlot itemSlot)
{
// If the item is equipped, unequip first
if (itemSlot is EquipmentSlot)
{
EquippableItem equippableItem = (EquippableItem)itemSlot.Item;
equippableItem.Unequip(this);
AdjustStatsIfNeeded();
UpdateStatValues();
}
itemSlot.Item.Destroy();
itemSlot.Item = null;
}
public void Equip(EquippableItem item)
{
if (Inventory.RemoveItem(item))
{
EquippableItem previousItem;
if (EquipmentPanel.AddItem(item, out previousItem))
{
if (previousItem != null)
{
Inventory.AddItem(previousItem);
previousItem.Unequip(this);
}
item.Equip(this);
}
else
{
Inventory.AddItem(item);
}
// Update stats immediately after equipping
UpdateStatValues();
AdjustStatsIfNeeded();
// Update weapon type
weaponTypeDetector.ManualUpdateWeaponType();
}
}
public void Unequip(EquippableItem item)
{
if (Inventory.CanAddItem(item) && EquipmentPanel.RemoveItem(item))
{
item.Unequip(this);
// Update stats immediately after unequipping
UpdateStatValues();
Inventory.AddItem(item);
// Reset current stats to their maximum values
AdjustStatsIfNeeded();
// Update weapon type
weaponTypeDetector.ManualUpdateWeaponType();
}
}
// Method to call SetCurrentStatsToMax from the Player script
public void AdjustStatsIfNeeded()
{
player.AdjustStatsIfNeeded();
}
public void UpdateMax()
{
player.UpdateMaxStats();
}
private ItemContainer openItemContainer;
public void OpenChest(Chest chest)
{
OpenItemContainer(chest);
}
public void CloseChest(Chest chest)
{
CloseItemContainer(chest);
}
BeginDrag, Drag, EndDrag, Drop: These methods handle the mechanics of dragging an item icon across the UI and placing it into other slots.
Seed Management:
InventoryRightClick and DeselectSeed: Manage user interactions related to selecting and deselecting seed items, enhancing user control over farming or planting mechanics.
Chest and Item Container Interaction:
Methods like OpenChest, CloseChest, TransferToItemContainer, and TransferToInventory: Facilitate item movement between inventory and item containers like chests.
Best Practices & Enhancements:
Code Modularity:
Consider breaking down this large script into separate components (e.g., InventoryManager, EquipmentManager, UIManager) to handle each part of functionality more independently.
Maintainability:
Check for any null references or potential bugs when dealing with item transfers, especially in complex UI interactions.
Optimization:
Ensure only necessary UI and stat updates are performed to reduce unnecessary performance overhead, particularly with frequent updates like in Update.
Single Responsibility Principle:
The Character class currently does many things. Each class should ideally be responsible for one aspect of the game (like handling stats, managing inventory, etc.).
This setup serves well for prototyping and smaller projects but as your project grows, aim for better separation of concerns and structured design patterns to manage complexity effectively.
public class Player : MonoBehaviour
{
// Other fields and methods...
public void LoadPlayerData(string playerName)
{
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
if (Directory.Exists(playerDirectory))
{
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
if (File.Exists(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = (PlayerData)formatter.Deserialize(fileStream);
// Ensure to set both current and max stats
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
// Load current and max stats separately
currentHealth = data.currentHealth;
maxHealth = data.maxHealth;
currentMana = data.currentMana;
maxMana = data.maxMana;
currentDefense = data.currentDefense;
maxDefense = data.maxDefense;
// Set other current stats and max stats similarly...
// Assuming LoadStatsFromData method sets max stats for character
character.LoadStatsFromData(data);
// Set the correct current stats after loading
SetCurrentStatsToLoadedValues();
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
Debug.Log("<color=#00FF00><b>Loaded PlayerData</b></color>");
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
else
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
}
}
}
private void SetCurrentStatsToLoadedValues()
{
// Ensure current values are being used appropriately post load
currentHealth = Mathf.Min(currentHealth, maxHealth);
currentMana = Mathf.Min(currentMana, maxMana);
currentDefense = Mathf.Min(currentDefense, maxDefense);
// Continue for other stats...
}
}
Explanation
Separate Loading of Current and Max Values: The code loads currentHealth, maxHealth, etc., separately ensuring that the saved values are correctly restored to the current and max fields.
Set Current Stats Post Loading: A helper method, SetCurrentStatsToLoadedValues(), ensures that after loading, current stats do not exceed their corresponding max values (if adjustments are needed post-load).
Refactor Common Functions: If setting current to a value less than max is common, encapsulate this logic in a utility function to ensure consistency and reduce repeated code. This makes the code cleaner and reduces chances of mistakes.
This should prevent your max stats from being incorrectly set to the current stat values and help maintain the separation between max and current stats across game loads. This adjustment assumes that your saved data reflects your game's intended design for storing these values.
}
using UnityEngine;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System;
public class Player : MonoBehaviour
{
#region Stats
public string PlayerName;
public int PlayerLevel;
public int CurrentEXP;
public int ExpToLevelUp;
public int currentHealth;
public int maxHealth;
public int currentMana;
public int maxMana;
public int currentDefense;
public int maxDefense;
public int currentAttack;
public int maxAttack;
public float currentAttackSpeed;
public float maxAttackSpeed;
public int currentCritical;
public int maxCritical;
public float currentLifeSteal;
public float maxLifeSteal;
public float currentRange;
public float maxRange;
public float currentElementalMastery;
public float maxElementalMastery;
public float currentSpeed;
public float maxSpeed;
public float currentCooldown;
public float maxCooldown;
public float currentKnockback;
public float maxKnockback;
public float currentRecovery;
public float maxRecovery;
public float currentEvade;
public float maxEvade;
public float currentFortune;
public float maxFortune;
public Character character; // Reference to the Character class
#endregion
public void LoadPlayerData(string playerName)
{
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
if (Directory.Exists(playerDirectory))
{
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
if (File.Exists(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = (PlayerData)formatter.Deserialize(fileStream);
// Ensure to set both current and max stats
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
currentHealth = data.currentHealth;
maxHealth = data.maxHealth;
currentMana = data.currentMana;
maxMana = data.maxMana;
currentDefense = data.currentDefense;
maxDefense = data.maxDefense;
currentAttack = data.currentAttack;
maxAttack = data.maxAttack;
currentAttackSpeed = data.currentAttackSpeed;
maxAttackSpeed = data.maxAttackSpeed;
currentCritical = data.currentCritical;
maxCritical = data.maxCritical;
currentLifeSteal = data.currentLifeSteal;
maxLifeSteal = data.maxLifeSteal;
currentRange = data.currentRange;
maxRange = data.maxRange;
currentElementalMastery = data.currentElementalMastery;
maxElementalMastery = data.maxElementalMastery;
currentSpeed = data.currentSpeed;
maxSpeed = data.maxSpeed;
currentCooldown = data.currentCooldown;
maxCooldown = data.maxCooldown;
currentKnockback = data.currentKnockback;
maxKnockback = data.maxKnockback;
currentRecovery = data.currentRecovery;
maxRecovery = data.maxRecovery;
currentEvade = data.currentEvade;
maxEvade = data.maxEvade;
currentFortune = data.currentFortune;
maxFortune = data.maxFortune;
// Load max stats into character for potential usage
character.LoadStatsFromData(data);
// Adjust current stats based on loaded max stats
SetCurrentStatsToLoadedValues();
// Set player position
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
Debug.Log("<color=#00FF00><b>Loaded PlayerData</b></color>");
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
else
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
}
}
}
private void SetCurrentStatsToLoadedValues()
{
// Ensure current values do not exceed max values after loading
currentHealth = Mathf.Min(currentHealth, maxHealth);
currentMana = Mathf.Min(currentMana, maxMana);
currentDefense = Mathf.Min(currentDefense, maxDefense);
currentAttack = Mathf.Min(currentAttack, maxAttack);
currentAttackSpeed = Mathf.Min(currentAttackSpeed, maxAttackSpeed);
currentCritical = Mathf.Min(currentCritical, maxCritical);
currentLifeSteal = Mathf.Min(currentLifeSteal, maxLifeSteal);
currentRange = Mathf.Min(currentRange, maxRange);
currentElementalMastery = Mathf.Min(currentElementalMastery, maxElementalMastery);
currentSpeed = Mathf.Min(currentSpeed, maxSpeed);
currentCooldown = Mathf.Min(currentCooldown, maxCooldown);
currentKnockback = Mathf.Min(currentKnockback, maxKnockback);
currentRecovery = Mathf.Min(currentRecovery, maxRecovery);
currentEvade = Mathf.Min(currentEvade, maxEvade);
currentFortune = Mathf.Min(currentFortune, maxFortune);
}
}
Key Adjustments:
Stat Initialization:
Correctly sets both current and max values for all relevant stats from the saved data.
Post-Load Adjustment:
Ensures that current stats are appropriately limited by their max values using Mathf.Min.
By following these refinements, you ensure that loading maintains the integrity of your player stats, keeping the separation between current and max values intact, and thereby preserving the player's progress accurately.
public void LoadPlayerData(string playerName)
{
// Construct the base directory path
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
code
// Check if the base directory exists
if (!Directory.Exists(baseDirectory))
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
return;
}
// Append the player's folder based on PlayerName
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
// Ensure the player's directory exists
if (!Directory.Exists(playerDirectory))
{
Debug.LogWarning($"<color=red><b>No saved data found for player: {PlayerName}</b></color>");
return;
}
// Construct the full file path
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
// Check if the file exists
if (File.Exists(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = formatter.Deserialize(fileStream) as PlayerData;
// Assign loaded data back to the player (optional, depends on your game's logic)
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
currentHealth = data.currentHealth;
maxHealth = data.maxHealth;
currentMana = data.currentMana;
maxMana = data.maxMana;
currentDefense = data.currentDefense;
maxDefense = data.maxDefense;
currentAttack = data.currentAttack;
maxAttack = data.maxAttack;
currentAttackSpeed = data.currentAttackSpeed;
maxAttackSpeed = data.maxAttackSpeed;
currentCritical = data.currentCritical;
maxCritical = data.maxCritical;
currentLifeSteal = data.currentLifeSteal;
maxLifeSteal = data.maxLifeSteal;
currentRange = data.currentRange;
maxRange = data.maxRange;
currentElementalMastery = data.currentElementalMastery;
maxElementalMastery = data.maxElementalMastery;
currentSpeed = data.currentSpeed;
maxSpeed = data.maxSpeed;
currentCooldown = data.currentCooldown;
maxCooldown = data.maxCooldown;
currentKnockback = data.currentKnockback;
maxKnockback = data.maxKnockback;
currentRecovery = data.currentRecovery;
maxRecovery = data.maxRecovery;
currentEvade = data.currentEvade;
maxEvade = data.maxEvade;
currentFortune = data.currentFortune;
maxFortune = data.maxFortune;
// Assuming 'character' is an instance of the Character class
character.LoadStatsFromData(data);
playerSkill.LoadSkillData(PlayerName);
// Position (example)
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
Debug.Log($"<color=#00FF00><b>Loaded PlayerData</b></color>");
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
else
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
}
}
#endregion
here pelase give me this fully corrected where i can load the game and save the game and the stats will be set to their values correctly , Current values to current values and max values to max values
ensure that when i save with missing health for example 500/ 1000hp that i load the current valeus of 500 hp and the max values of 1000hp
because i seem to have an issue where i load the game after i save i come across this bug where max health seem to become current health values , i load the game and i have current 500hp over current 500hp
instead of current 500hp over 1000 max hp
using UnityEngine;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class Player : MonoBehaviour
{
#region Stats
public string PlayerName;
public int PlayerLevel;
public int CurrentEXP;
public int ExpToLevelUp;
public int currentHealth;
public int maxHealth;
public int currentMana;
public int maxMana;
public int currentDefense;
public int maxDefense;
public int currentAttack;
public int maxAttack;
public float currentAttackSpeed;
public float maxAttackSpeed;
public int currentCritical;
public int maxCritical;
public float currentLifeSteal;
public float maxLifeSteal;
public float currentRange;
public float maxRange;
public float currentElementalMastery;
public float maxElementalMastery;
public float currentSpeed;
public float maxSpeed;
public float currentCooldown;
public float maxCooldown;
public float currentKnockback;
public float maxKnockback;
public float currentRecovery;
public float maxRecovery;
public float currentEvade;
public float maxEvade;
public float currentFortune;
public float maxFortune;
public Character character; // Reference to the Character class
public PlayerSkill playerSkill; // Reference to PlayerSkill
#endregion
#region Save And Load System
public void SavePlayerData()
{
PlayerData data = new PlayerData
{
playerName = PlayerName,
playerLevel = PlayerLevel,
currentEXP = CurrentEXP,
expToLevelUp = ExpToLevelUp,
currentHealth = currentHealth,
maxHealth = maxHealth,
currentMana = currentMana,
maxMana = maxMana,
currentDefense = currentDefense,
maxDefense = maxDefense,
currentAttack = currentAttack,
maxAttack = maxAttack,
currentAttackSpeed = currentAttackSpeed,
maxAttackSpeed = maxAttackSpeed,
currentCritical = currentCritical,
maxCritical = maxCritical,
currentLifeSteal = currentLifeSteal,
maxLifeSteal = maxLifeSteal,
currentRange = currentRange,
maxRange = maxRange,
currentElementalMastery = currentElementalMastery,
maxElementalMastery = maxElementalMastery,
currentSpeed = currentSpeed,
maxSpeed = maxSpeed,
currentCooldown = currentCooldown,
maxCooldown = maxCooldown,
currentKnockback = currentKnockback,
maxKnockback = maxKnockback,
currentRecovery = currentRecovery,
maxRecovery = maxRecovery,
currentEvade = currentEvade,
maxEvade = maxEvade,
currentFortune = currentFortune,
maxFortune = maxFortune,
playerPosX = transform.position.x,
playerPosY = transform.position.y,
playerPosZ = transform.position.z
};
string saveDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA", PlayerName);
string fileName = $"{PlayerName}_Data.sav";
string savePath = Path.Combine(saveDirectory, fileName);
try
{
Directory.CreateDirectory(saveDirectory);
using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fileStream, data);
}
Debug.Log($"<color=#ADD8E6><b>Player data saved successfully</b></color> to: {savePath}");
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to save player data: {e.Message}</b></color>");
}
}
public void LoadPlayerData(string playerName)
{
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
if (Directory.Exists(playerDirectory))
{
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
if (File.Exists(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = (PlayerData)formatter.Deserialize(fileStream);
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
// Restore current and max stats separately
currentHealth = data.currentHealth;
maxHealth = data.maxHealth;
currentMana = data.currentMana;
maxMana = data.maxMana;
currentDefense = data.currentDefense;
maxDefense = data.maxDefense;
currentAttack = data.currentAttack;
maxAttack = data.maxAttack;
currentAttackSpeed = data.currentAttackSpeed;
maxAttackSpeed = data.maxAttackSpeed;
currentCritical = data.currentCritical;
maxCritical = data.maxCritical;
currentLifeSteal = data.currentLifeSteal;
maxLifeSteal = data.maxLifeSteal;
currentRange = data.currentRange;
maxRange = data.maxRange;
currentElementalMastery = data.currentElementalMastery;
maxElementalMastery = data.maxElementalMastery;
currentSpeed = data.currentSpeed;
maxSpeed = data.maxSpeed;
currentCooldown = data.currentCooldown;
maxCooldown = data.maxCooldown;
currentKnockback = data.currentKnockback;
maxKnockback = data.maxKnockback;
currentRecovery = data.currentRecovery;
maxRecovery = data.maxRecovery;
currentEvade = data.currentEvade;
maxEvade = data.maxEvade;
currentFortune = data.currentFortune;
maxFortune = data.maxFortune;
character.LoadStatsFromData(data);
playerSkill.LoadSkillData(PlayerName);
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
Debug.Log($"<color=#00FF00><b>Loaded PlayerData</b></color>");
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
else
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
}
}
else
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
}
}
#endregion
}
[Serializable]
public class PlayerData
{
public string playerName;
public int playerLevel;
public int currentEXP;
public int expToLevelUp;
public int currentHealth;
public int maxHealth;
public int currentMana;
public int maxMana;
public int currentDefense;
public int maxDefense;
public int currentAttack;
public int maxAttack;
public float currentAttackSpeed;
public float maxAttackSpeed;
public int currentCritical;
public int maxCritical;
public float currentLifeSteal;
public float maxLifeSteal;
public float currentRange;
public float maxRange;
public float currentElementalMastery;
public float maxElementalMastery;
public float currentSpeed;
public float maxSpeed;
public float currentCooldown;
public float maxCooldown;
public float currentKnockback;
public float maxKnockback;
public float currentRecovery;
public float maxRecovery;
public float currentEvade;
public float maxEvade;
public float currentFortune;
public float maxFortune;
public float playerPosX;
public float playerPosY;
public float playerPosZ;
}
Key Adjustments:
Separation of Current and Max Stats: The code clearly separates the current and max stats for each attribute, ensuring that currentHealth and maxHealth (for example) are distinct and are both saved and restored independently.
Consistent Serialization/Deserialization: By maintaining this consistency in saving/loading operations, you ensure that when you save with a specific currentHealth and maxHealth, the same values will be restored, avoiding any mix-ups that might set max values to current states.
This setup ensures that you correctly save and retrieve stat values, preserving player progress accurately, even when exiting and reloading the game.
using UnityEngine;
using UnityEngine.UI;
using W.o.N_Stats;
using System;
using System.Collections;
using UnityEngine.EventSystems;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class Player : MonoBehaviour
{
#region Stats Name And Player Info
// Property to set or get the player name
public string PlayerName
{
get { return PlayerPrefs.GetString("PlayerName", "Default Name"); }
set { PlayerPrefs.SetString("PlayerName", value); }
}
[Header("Level and Experience")]
public int PlayerLevel;
public int CurrentEXP;
public int ExpToLevelUp;
[Header("Health")]
public int currentHealth;
public int maxHealth;
[Header("Mana")]
public int currentMana;
public int maxMana;
[Header("Defense")]
public int currentDefense;
public int maxDefense;
[Header("Attack")]
public int currentAttack;
public int maxAttack;
[Header("Attack Speed")]
public float currentAttackSpeed;
public float maxAttackSpeed;
[Header("Critical")]
public int currentCritical;
public int maxCritical;
[Header("Life Steal")]
public float currentLifeSteal;
public float maxLifeSteal;
[Header("Range")]
public float currentRange;
public float maxRange;
[Header("Elemental Mastery")]
public float currentElementalMastery;
public float maxElementalMastery;
[Header("Cooldown")]
public float currentCooldown;
public float maxCooldown;
[Header("Knockback")]
public float currentKnockback;
public float maxKnockback;
[Header("Speed")]
public float currentSpeed;
public float maxSpeed;
[Header("Recovery")]
public float currentRecovery;
public float maxRecovery;
[Header("Evade")]
public float currentEvade;
public float maxEvade;
[Header("Fortune")]
public float currentFortune;
public float maxFortune;
[Header("Character and Stat Panel")]
public Character character;
public StatPanel statPanel;
public PlayerSkill playerSkill;
public Inventory inventory;
public EquipmentPanel equipmentPanel;
[Header("Hurt Effect")]
[SerializeField] private GameObject hurtParticlePrefab;
[SerializeField]
private PlayerDamageIndicator damageIndicatorScript; // Reference to the PlayerDamageIndicator script
public PlayerLevelUpText levelUpTextScript; // Reference to the PlayerLevelUpText script
#endregion
private float lastDamageTime = 0f; // Track the time of the last damage taken or mana used
private float lastRecoveryTime = 0f;
private bool hasEquippedItemRecently = false;
private float timeSinceEquippingItem = 0f;
private float equipItemRecoveryDelay = 30f;
[Header("Player Camera")]
public Camera playerCamera; // Assign the player's camera directly in the inspector
[Header("Button Assignment")]
public float attackRange = 2f;
public LayerMask mobsLayer; // Specify the layer for "Mobs"
[SerializeField] private bool displayGizmo = true; // Toggle to display Gizmo
// Event to notify UI that stats have changed
public Action OnStatsChanged { get; set; }
private void OnDrawGizmos()
{
if (displayGizmo)
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}
// Method to update the player's name
public void UpdatePlayerName(string newName)
{
PlayerName = newName;
}
#region Take Damage & Respawn
code
public void TakeDamage(int damage)
{
// Spawn the hurt particle effect if the prefab is assigned
if (hurtParticlePrefab != null)
{
GameObject hurtParticle = Instantiate(hurtParticlePrefab, transform.position, Quaternion.identity);
Destroy(hurtParticle, 0.45f); // Destroy the particle effect after 0.45 seconds
}
// Call the ShowDamageText method from PlayerDamageIndicator script and pass the damage value
if (damageIndicatorScript != null)
{
damageIndicatorScript.ShowDamageText(damage);
}
// Check if the player can evade
if (UnityEngine.Random.Range(0f, 100f) <= currentEvade)
{
Debug.Log($"{PlayerName} Evaded the Attack & Avoided {damage} Damage!");
}
else
{
// Calculate actual damage after considering defense
int actualDamage = Mathf.Max(0, damage - currentDefense);
// Damage defense first if there's any
if (currentDefense > 0)
{
int defenseDamage = Mathf.Max(0, damage - actualDamage);
currentDefense = Mathf.Max(0, currentDefense - damage);
// Log damage taken to defense if defense is greater than 0
if (defenseDamage > 0)
{
Debug.Log($"{PlayerName} Defense took {defenseDamage} damage!");
}
}
// If defense is reduced to 0, or no defense, damage health
if (currentDefense == 0)
{
int healthDamage = actualDamage;
currentHealth -= healthDamage;
// Log the health damage
Debug.Log($"{PlayerName} took {healthDamage} damage to health!");
// Check if health reaches 0
if (currentHealth <= 0)
{
Debug.Log($"{PlayerName} Died!");
// Respawn the player at the saved location and restore all stats to full
LoadPlayerData(PlayerName); // Respawn the player using saved data
RespawnPlayer();
}
}
}
// Update the last damage time to trigger recovery
lastDamageTime = Time.time;
}
private void RespawnPlayer()
{
// Restore all stats to full
SetCurrentStatsToMax(); // Reset current stats to their maximum values
// Teleport the player back to the saved location using the PlayerSaveLocation script
PlayerSaveLocation saveLocationScript = GetComponent<PlayerSaveLocation>();
if (saveLocationScript != null)
{
saveLocationScript.TeleportToSavedLocation();
}
}
#endregion
#region Start And Update
void Start()
{
// Construct the base directory path
code
SetStartingStats(); // Call this method to set starting stats
InitializeStats();
SetCurrentStatsToMax();
// Set the initial values for level and experience
PlayerLevel = 1;
CurrentEXP = 0;
ExpToLevelUp = 250;
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA", PlayerName);
// Check if the player's directory exists
if (Directory.Exists(baseDirectory))
{
// Construct the full file path for the player's data file
string filePath = Path.Combine(baseDirectory, $"{PlayerName}_Data.sav");
// Check if the player's data file exists
if (File.Exists(filePath))
{
// Load player data from file
LoadPlayerData(PlayerName);
}
}
}
private void Update()
{
// This Bellow When An Item Is Equipped It Will Update The Stats on Both The UI And The Player
UpdateMaxStats();
// Check if enough time has passed since the last damage or mana/defense depletion
if (!hasEquippedItemRecently && Time.time - lastDamageTime >= 30f)
{
// Increment current health, mana, and defense towards their maximum values over time
if (Time.time - lastRecoveryTime >= 5f) // Check if 5 seconds have passed since last recovery
{
// Increment stats by maxRecovery amount
currentHealth = Mathf.Min(maxHealth, currentHealth + Mathf.RoundToInt(maxRecovery));
currentMana = Mathf.Min(maxMana, currentMana + Mathf.RoundToInt(maxRecovery));
currentDefense = Mathf.Min(maxDefense, currentDefense + Mathf.RoundToInt(maxRecovery));
// Update the last recovery time
lastRecoveryTime = Time.time;
}
}
// Update the time since equipping an item
if (hasEquippedItemRecently)
{
timeSinceEquippingItem += Time.deltaTime;
if (timeSinceEquippingItem >= equipItemRecoveryDelay)
{
// Enough time has passed after equipping an item, reset the flag and trigger recovery
hasEquippedItemRecently = false;
lastDamageTime = Time.time;
}
}
}
#endregion
#region Level Up
public void LevelUp()
{
// Call the LevelUpText method from PlayerLevelUpText script
if (levelUpTextScript != null)
{
levelUpTextScript.ShowLevelUpText();
}
code
PlayerLevel++;
CurrentEXP -= ExpToLevelUp;
ExpToLevelUp *= 2;
// Update character stats
character.Health.BaseValue += 5 * PlayerLevel;
character.Mana.BaseValue += 2 * PlayerLevel;
character.Defence.BaseValue += 1 * PlayerLevel;
character.Attack.BaseValue += 1 * PlayerLevel;
character.AttackSpeed.BaseValue += 0.008f * PlayerLevel;
character.Critical.BaseValue += 0.05F * PlayerLevel;
character.LifeSteal.BaseValue += 0.5f * PlayerLevel;
character.Range.BaseValue += 0.015f * PlayerLevel;
character.ElementalMastery.BaseValue += 0.13f * PlayerLevel;
character.Cooldown.BaseValue += 0.1f * PlayerLevel;
character.Knockback.BaseValue += 0.025f * PlayerLevel;
character.Speed.BaseValue += 0.005f * PlayerLevel;
character.Recovery.BaseValue += 0.5f * PlayerLevel;
character.Evade.BaseValue += 0.01f * PlayerLevel;
character.Fortune.BaseValue += 0.015f * PlayerLevel;
// Update stat values
character.UpdateStatValues();
// Update max stats
UpdateMaxStats();
// Set current stats to max
SetCurrentStatsToMax();
// Show updated stats on UI
statPanel.SetStats(character.Health, character.Mana, character.Defence, character.Attack , character.AttackSpeed, character.Critical, character.LifeSteal, character.Range, character.ElementalMastery, character.Speed, character.Cooldown, character.Knockback, character.Recovery, character.Evade, character.Fortune);
}
#endregion
private void SetStartingStats()
{
// Set starting stats for the player based on character stats
currentHealth = (int)character.Health.Value;
maxHealth = (int)character.Health.Value;
currentMana = (int)character.Mana.Value;
maxMana = (int)character.Mana.Value;
currentDefense = (int)character.Defence.Value;
maxDefense = (int)character.Defence.Value;
currentAttack = (int)character.Attack.Value;
maxAttack = (int)character.Attack.Value;
currentAttackSpeed = character.AttackSpeed.Value;
maxAttackSpeed = character.AttackSpeed.Value;
currentCritical = (int)character.Critical.Value;
maxCritical = (int)character.Critical.Value;
currentLifeSteal = character.LifeSteal.Value;
maxLifeSteal = character.LifeSteal.Value;
currentRange = character.Range.Value;
maxRange = character.Range.Value;
currentElementalMastery = character.ElementalMastery.Value;
maxElementalMastery = character.ElementalMastery.Value;
currentSpeed = character.Speed.Value;
maxSpeed = character.Speed.Value;
currentCooldown = character.Cooldown.Value;
maxCooldown = character.Cooldown.Value;
currentKnockback = character.Knockback.Value;
maxKnockback = character.Knockback.Value;
currentRecovery = character.Recovery.Value;
maxRecovery = character.Recovery.Value;
currentEvade = character.Evade.Value;
maxEvade = character.Evade.Value;
currentFortune = character.Fortune.Value;
maxFortune = character.Fortune.Value;
// Call UpdateStatValues to apply the changes
character.UpdateStatValues();
// Update max and current stats
UpdateMaxStats();
SetCurrentStatsToMax();
}
// Update the maximum stats of the character
public void UpdateMaxStats()
{
// Update max stats for the player based on character stats
maxHealth = (int)character.Health.Value;
maxMana = (int)character.Mana.Value;
maxDefense = (int)character.Defence.Value;
maxAttack = (int)character.Attack.Value;
maxAttackSpeed = character.AttackSpeed.Value;
maxCritical = (int)character.Critical.Value;
maxLifeSteal = character.LifeSteal.Value;
maxRange = character.Range.Value;
maxElementalMastery = character.ElementalMastery.Value;
maxSpeed = character.Speed.Value;
maxCooldown = character.Cooldown.Value;
maxKnockback = character.Knockback.Value;
maxRecovery = character.Recovery.Value;
maxEvade = character.Evade.Value;
maxFortune = character.Fortune.Value;
}
// Check if any current stats have changed due to equipping items
public void CurrentStatsChange()
{
// Mark that an item has been equipped recently
hasEquippedItemRecently = true;
timeSinceEquippingItem = 0f;
}
public void InitializeStats()
{
// Update max stats
UpdateMaxStats();
// Initialize current stats
maxHealth = Mathf.RoundToInt(character.Health.Value);
currentHealth = maxHealth;
maxMana = Mathf.RoundToInt(character.Mana.Value);
currentMana = maxMana;
maxDefense = Mathf.RoundToInt(character.Defence.Value);
currentDefense = maxDefense;
maxAttack = Mathf.RoundToInt(character.Attack.Value);
currentAttack = maxAttack;
maxAttackSpeed = character.AttackSpeed.Value;
currentAttackSpeed = maxAttackSpeed;
maxCritical = Mathf.RoundToInt(character.Critical.Value);
currentCritical = maxCritical;
maxLifeSteal = Mathf.RoundToInt(character.LifeSteal.Value);
currentLifeSteal = maxLifeSteal;
maxRange = Mathf.RoundToInt(character.Range.Value);
currentRange = maxRange;
maxElementalMastery = Mathf.RoundToInt(character.ElementalMastery.Value);
currentElementalMastery = maxElementalMastery;
maxSpeed = Mathf.RoundToInt(character.Speed.Value);
currentSpeed = maxSpeed;
maxCooldown = character.Cooldown.Value;
currentCooldown = maxCooldown;
maxKnockback = Mathf.RoundToInt(character.Knockback.Value);
currentKnockback = maxKnockback;
maxRecovery = character.Recovery.Value;
currentRecovery = maxRecovery;
maxEvade = character.Evade.Value;
currentEvade = maxEvade;
maxFortune = Mathf.RoundToInt(character.Fortune.Value);
currentFortune = maxFortune;
// Replace UpdateCurrentStats with the appropriate method
// (e.g., SetCurrentStatsToMax or any other method that updates your current stats)
SetCurrentStatsToMax();
}
public void SetCurrentStatsToMax()
{
currentHealth = maxHealth;
currentMana = maxMana;
currentDefense = maxDefense;
currentAttack = maxAttack;
currentAttackSpeed = maxAttackSpeed;
currentCritical = maxCritical;
currentLifeSteal = maxLifeSteal;
currentRange = maxRange;
currentElementalMastery = maxElementalMastery;
currentCooldown = maxCooldown;
currentKnockback = maxKnockback;
currentSpeed = maxSpeed;
currentRecovery = maxRecovery;
currentEvade = maxEvade;
currentFortune = maxFortune;
// Reset the last recovery time to prevent immediate recovery
lastRecoveryTime = Time.time;
}
public void AdjustStatsIfNeeded()
{
// Health
int newMaxHealth = Mathf.RoundToInt(character.Health.Value);
if (newMaxHealth < currentHealth)
{
currentHealth = newMaxHealth;
}
// Mana
int newMaxMana = Mathf.RoundToInt(character.Mana.Value);
if (newMaxMana < currentMana)
{
currentMana = newMaxMana;
}
// Defense
int newMaxDefense = Mathf.RoundToInt(character.Defence.Value);
if (newMaxDefense < currentDefense)
{
currentDefense = newMaxDefense;
}
// Attack
int newMaxAttack = Mathf.RoundToInt(character.Attack.Value);
if (newMaxAttack < currentAttack)
{
currentAttack = newMaxAttack;
}
// Attack Speed
float newMaxAttackSpeed = character.AttackSpeed.Value;
if (newMaxAttackSpeed < currentAttackSpeed)
{
currentAttackSpeed = newMaxAttackSpeed;
}
// Critical
int newMaxCritical = Mathf.RoundToInt(character.Critical.Value);
if (newMaxCritical < currentCritical)
{
currentCritical = newMaxCritical;
}
// LifeSteal
int newMaxLifeSteal = Mathf.RoundToInt(character.LifeSteal.Value);
if (newMaxLifeSteal < currentLifeSteal)
{
currentLifeSteal = newMaxLifeSteal;
}
// Range
int newMaxRange = Mathf.RoundToInt(character.Range.Value);
if (newMaxRange < currentRange)
{
currentRange = newMaxRange;
}
// ElementalMastery
int newMaxElementalMastery = Mathf.RoundToInt(character.ElementalMastery.Value);
if (newMaxElementalMastery < currentElementalMastery)
{
currentElementalMastery = newMaxElementalMastery;
}
// Speed
float newMaxSpeed = character.Speed.Value;
if (newMaxSpeed < currentSpeed)
{
currentSpeed = newMaxSpeed;
}
// Cooldown
float newMaxCooldown = character.Cooldown.Value;
if (newMaxCooldown < currentCooldown)
{
currentCooldown = newMaxCooldown;
}
// Knockback
int newMaxKnockback = Mathf.RoundToInt(character.Knockback.Value);
if (newMaxKnockback < currentKnockback)
{
currentKnockback = newMaxKnockback;
}
// Recovery
float newMaxRecovery = character.Recovery.Value;
if (newMaxRecovery < currentRecovery)
{
currentRecovery = newMaxRecovery;
}
// Evade
float newMaxEvade = character.Evade.Value;
if (newMaxEvade < currentEvade)
{
currentEvade = newMaxEvade;
}
// Fortune
int newMaxFortune = Mathf.RoundToInt(character.Fortune.Value);
if (newMaxFortune < currentFortune)
{
currentFortune = newMaxFortune;
}
CurrentStatsChange();
}
public void IncreaseExperience(int amount)
{
CurrentEXP += amount;
while (CurrentEXP >= ExpToLevelUp)
{
LevelUp();
}
}
public void AddStats(int healthToAdd, int defenseToAdd, int manaToAdd)
{
// Check if adding health would exceed the maximum
if (currentHealth < maxHealth)
{
// Calculate the new health after adding
int newHealth = currentHealth + healthToAdd;
// Ensure the new health doesn't exceed the maximum
newHealth = Mathf.Clamp(newHealth, 0, maxHealth);
// If the new health is different from the current health, apply the change
if (newHealth != currentHealth)
{
currentHealth = newHealth;
CurrentStatsChange(); // Notify stats change if needed
}
}
// Check if adding defense would exceed the maximum
if (currentDefense < maxDefense)
{
// Calculate the new defense after adding
int newDefense = currentDefense + defenseToAdd;
// Ensure the new defense doesn't exceed the maximum
newDefense = Mathf.Clamp(newDefense, 0, maxDefense);
// If the new defense is different from the current defense, apply the change
if (newDefense != currentDefense)
{
currentDefense = newDefense;
CurrentStatsChange(); // Notify stats change if needed
}
}
// Check if adding mana would exceed the maximum
if (currentMana < maxMana)
{
// Calculate the new mana after adding
int newMana = currentMana + manaToAdd;
// Ensure the new mana doesn't exceed the maximum
newMana = Mathf.Clamp(newMana, 0, maxMana);
// If the new mana is different from the current mana, apply the change
if (newMana != currentMana)
{
currentMana = newMana;
CurrentStatsChange(); // Notify stats change if needed
}
}
}
// This allows the UsableItem to start coroutines on the player
public new Coroutine StartCoroutine(IEnumerator routine)
{
return base.StartCoroutine(routine);
}
#region Save And Load System
code
public void SavePlayerData()
{
// Create a PlayerData object and populate it with current player state
PlayerData data = new PlayerData();
data.playerName = PlayerName;
data.playerLevel = PlayerLevel;
data.currentEXP = CurrentEXP;
data.expToLevelUp = ExpToLevelUp;
data.currentHealth = currentHealth;
data.maxHealth = maxHealth;
data.currentMana = currentMana;
data.maxMana = maxMana;
data.currentDefense = currentDefense;
data.maxDefense = maxDefense;
data.currentAttack = currentAttack;
data.maxAttack = maxAttack;
data.currentAttackSpeed = currentAttackSpeed;
data.maxAttackSpeed = maxAttackSpeed;
data.currentCritical = currentCritical;
data.maxCritical = maxCritical;
data.currentLifeSteal = currentLifeSteal;
data.maxLifeSteal = maxLifeSteal;
data.currentRange = currentRange;
data.maxRange = maxRange;
data.currentElementalMastery = currentElementalMastery;
data.maxElementalMastery = maxElementalMastery;
data.currentSpeed = currentSpeed;
data.maxSpeed = maxSpeed;
data.currentCooldown = currentCooldown;
data.maxCooldown = maxCooldown;
data.currentKnockback = currentKnockback;
data.maxKnockback = maxKnockback;
data.currentRecovery = currentRecovery;
data.maxRecovery = maxRecovery;
data.currentEvade = currentEvade;
data.maxEvade = maxEvade;
data.currentFortune = currentFortune;
data.maxFortune = maxFortune;
data.playerPosX = transform.position.x;
data.playerPosY = transform.position.y;
data.playerPosZ = transform.position.z;
// Adjusted file path
string saveDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA", PlayerName);
string fileName = $"{PlayerName}_Data.sav"; // Adjusted file name here
string savePath = Path.Combine(saveDirectory, fileName);
try
{
// Create directory if it doesn't exist
Directory.CreateDirectory(saveDirectory);
using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fileStream, data);
}
Debug.Log($"<color=#ADD8E6><b>Player data saved successfully</b></color> to: {savePath}");
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to save player data: {e.Message}</b></color>");
}
}
public void LoadPlayerData(string playerName)
{
// Construct the base directory path
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
code
// Check if the base directory exists
if (!Directory.Exists(baseDirectory))
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
return;
}
// Append the player's folder based on PlayerName
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
// Ensure the player's directory exists
if (!Directory.Exists(playerDirectory))
{
Debug.LogWarning($"<color=red><b>No saved data found for player: {PlayerName}</b></color>");
return;
}
// Construct the full file path
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
// Check if the file exists
if (File.Exists(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = formatter.Deserialize(fileStream) as PlayerData;
// Assign loaded data back to the player (optional, depends on your game's logic)
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
currentHealth = data.currentHealth;
maxHealth = data.maxHealth;
currentMana = data.currentMana;
maxMana = data.maxMana;
currentDefense = data.currentDefense;
maxDefense = data.maxDefense;
currentAttack = data.currentAttack;
maxAttack = data.maxAttack;
currentAttackSpeed = data.currentAttackSpeed;
maxAttackSpeed = data.maxAttackSpeed;
currentCritical = data.currentCritical;
maxCritical = data.maxCritical;
currentLifeSteal = data.currentLifeSteal;
maxLifeSteal = data.maxLifeSteal;
currentRange = data.currentRange;
maxRange = data.maxRange;
currentElementalMastery = data.currentElementalMastery;
maxElementalMastery = data.maxElementalMastery;
currentSpeed = data.currentSpeed;
maxSpeed = data.maxSpeed;
currentCooldown = data.currentCooldown;
maxCooldown = data.maxCooldown;
currentKnockback = data.currentKnockback;
maxKnockback = data.maxKnockback;
currentRecovery = data.currentRecovery;
maxRecovery = data.maxRecovery;
currentEvade = data.currentEvade;
maxEvade = data.maxEvade;
currentFortune = data.currentFortune;
maxFortune = data.maxFortune;
// Assuming 'character' is an instance of the Character class
character.LoadStatsFromData(data);
playerSkill.LoadSkillData(PlayerName);
// Position (example)
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
Debug.Log($"<color=#00FF00><b>Loaded PlayerData</b></color>");
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
else
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
}
}
#endregion
}
#region Save And Load System
public void SavePlayerData()
{
// Create a PlayerData object and populate it with current player state
PlayerData data = new PlayerData()
{
playerName = PlayerName,
playerLevel = PlayerLevel,
currentEXP = CurrentEXP,
expToLevelUp = ExpToLevelUp,
currentHealth = currentHealth,
maxHealth = maxHealth,
currentMana = currentMana,
maxMana = maxMana,
currentDefense = currentDefense,
maxDefense = maxDefense,
currentAttack = currentAttack,
maxAttack = maxAttack,
currentAttackSpeed = currentAttackSpeed,
maxAttackSpeed = maxAttackSpeed,
currentCritical = currentCritical,
maxCritical = maxCritical,
currentLifeSteal = currentLifeSteal,
maxLifeSteal = maxLifeSteal,
currentRange = currentRange,
maxRange = maxRange,
currentElementalMastery = currentElementalMastery,
maxElementalMastery = maxElementalMastery,
currentSpeed = currentSpeed,
maxSpeed = maxSpeed,
currentCooldown = currentCooldown,
maxCooldown = maxCooldown,
currentKnockback = currentKnockback,
maxKnockback = maxKnockback,
currentRecovery = currentRecovery,
maxRecovery = maxRecovery,
currentEvade = currentEvade,
maxEvade = maxEvade,
currentFortune = currentFortune,
maxFortune = maxFortune,
playerPosX = transform.position.x,
playerPosY = transform.position.y,
playerPosZ = transform.position.z
};
string saveDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA", PlayerName);
string fileName = $"{PlayerName}_Data.sav";
string savePath = Path.Combine(saveDirectory, fileName);
try
{
Directory.CreateDirectory(saveDirectory);
using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fileStream, data);
}
Debug.Log($"<color=#ADD8E6><b>Player data saved successfully</b></color> to: {savePath}");
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to save player data: {e.Message}</b></color>");
}
}
public void LoadPlayerData(string playerName)
{
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
if (!Directory.Exists(playerDirectory))
{
Debug.LogWarning($"<color=red><b>No saved data found for player: {PlayerName}</b></color>");
return;
}
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
if (!File.Exists(filePath))
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
return;
}
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = formatter.Deserialize(fileStream) as PlayerData;
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
// Load current and max stats correctly
currentHealth = data.currentHealth;
maxHealth = data.maxHealth;
currentMana = data.currentMana;
maxMana = data.maxMana;
currentDefense = data.currentDefense;
maxDefense = data.maxDefense;
currentAttack = data.currentAttack;
maxAttack = data.maxAttack;
currentAttackSpeed = data.currentAttackSpeed;
maxAttackSpeed = data.maxAttackSpeed;
currentCritical = data.currentCritical;
maxCritical = data.maxCritical;
currentLifeSteal = data.currentLifeSteal;
maxLifeSteal = data.maxLifeSteal;
currentRange = data.currentRange;
maxRange = data.maxRange;
currentElementalMastery = data.currentElementalMastery;
maxElementalMastery = data.maxElementalMastery;
currentSpeed = data.currentSpeed;
maxSpeed = data.maxSpeed;
currentCooldown = data.currentCooldown;
maxCooldown = data.maxCooldown;
currentKnockback = data.currentKnockback;
maxKnockback = data.maxKnockback;
currentRecovery = data.currentRecovery;
maxRecovery = data.maxRecovery;
currentEvade = data.currentEvade;
maxEvade = data.maxEvade;
currentFortune = data.currentFortune;
maxFortune = data.maxFortune;
// Update Character and other dependencies as needed
character.LoadStatsFromData(data);
playerSkill.LoadSkillData(PlayerName);
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
Debug.Log($"<color=#00FF00><b>Loaded PlayerData</b></color>");
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
#endregion
Important Steps:
Direct and Distinct Assignments: Ensure that the assignments during data loading from the PlayerData object to your player’s fields (currentHealth, maxHealth, etc.) are correct and direct.
Post-Load State Consistency: After loading, confirm no logic automatically modifies currentHealth directly after setting it from loaded data, unless intended for a specific game mechanic (e.g., heal on load).
Remove or Double-Check Other Initial Sets: In your Start, SetStartingStats, InitializeStats, or other methods that initialize or reset stats, ensure these initialization blocks do not override your loaded values unless explicitly required for design purposes.
Debugging: Add debug logs as needed to track values before and after loading to easily catch unexpected changes. For example:
PlayerData Integrity: Double-check that the PlayerData object received by LoadPlayerData has its fields correctly assigned during serialization and deserialization.
By carefully controlling the loading and post-load handling of your stats, this setup should correctly restore the player's progress as expected, reflecting the difference between current and max values appropriately.
}
Conclusion:
The current setup should correctly display the loaded values on the UI, provided that:
The player’s data is correctly restored into the Player script’s current and max fields.
The OnStatsChanged event is invoked after loading to notify the UI of new stat values.
Any values that directly impact the UI like max and current health, mana, etc., need to be properly set during the loading process as discussed.
These approaches ensure that your UI reflects the current game state accurately and promptly, especially following significant game events like loading a save.
public void LoadPlayerData(string playerName)
{
// Construct the base directory path
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
if (!Directory.Exists(playerDirectory))
{
Debug.LogWarning($"<color=red><b>No saved data found for player: {PlayerName}</b></color>");
return;
}
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
if (!File.Exists(filePath))
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
return;
}
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = formatter.Deserialize(fileStream) as PlayerData;
if (data != null)
{
// Load basic player info
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
// Load current and max stats
currentHealth = data.currentHealth;
maxHealth = data.maxHealth;
currentMana = data.currentMana;
maxMana = data.maxMana;
currentDefense = data.currentDefense;
maxDefense = data.maxDefense;
currentAttack = data.currentAttack;
maxAttack = data.maxAttack;
currentAttackSpeed = data.currentAttackSpeed;
maxAttackSpeed = data.maxAttackSpeed;
currentCritical = data.currentCritical;
maxCritical = data.maxCritical;
currentLifeSteal = data.currentLifeSteal;
maxLifeSteal = data.maxLifeSteal;
currentRange = data.currentRange;
maxRange = data.maxRange;
currentElementalMastery = data.currentElementalMastery;
maxElementalMastery = data.maxElementalMastery;
currentSpeed = data.currentSpeed;
maxSpeed = data.maxSpeed;
currentCooldown = data.currentCooldown;
maxCooldown = data.maxCooldown;
currentKnockback = data.currentKnockback;
maxKnockback = data.maxKnockback;
currentRecovery = data.currentRecovery;
maxRecovery = data.maxRecovery;
currentEvade = data.currentEvade;
maxEvade = data.maxEvade;
currentFortune = data.currentFortune;
maxFortune = data.maxFortune;
// Assume 'character' is an instance of the Character class and load stats to it
character.LoadStatsFromData(data);
// Assume 'playerSkill' is valid and load skills related to player
playerSkill.LoadSkillData(PlayerName);
// Update player position
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
Debug.Log($"<color=#00FF00><b>Loaded PlayerData</b></color>");
// Trigger the stats changed event to update UI
OnStatsChanged?.Invoke();
// Manually update UI to ensure correct display of loaded stats
FindObjectOfType<PlayerUI>()?.UpdateUI();
}
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
Key Points:
Directory and File Checks: It ensures that the directory and file exist before attempting to load them.
Binary Serialization: This code uses BinaryFormatter to deserialize the PlayerData object.
Exact Field Mapping: Each piece of player data is separately loaded into the player's fields (currentHealth, maxHealth, etc.).
UI Update: After loading the player's data, the OnStatsChanged event is invoked to notify any subscribed UI elements of the change. Additionally, a direct call to UpdateUI is made to ensure immediate UI updates.
Note:
Make sure to test this in your environment to verify the persistence of data types and serialization format matches any possible changes you might have included beyond the example provided. The FindObjectOfType<PlayerUI>() call retrieves the PlayerUI component, provided there's one in the scene hierarchy, to explicitly update the UI. Adjust based on the specific way your game handles UI component references if necessary.
public class Player : MonoBehaviour
{
#region Stats Name And Player Info
// Property to set or get the player name
public string PlayerName
{
get { return PlayerPrefs.GetString("PlayerName", "Default Name"); }
set { PlayerPrefs.SetString("PlayerName", value); }
}
[Header("Level and Experience")]
public int PlayerLevel;
public int CurrentEXP;
public int ExpToLevelUp;
[Header("Health")]
public int currentHealth;
public int maxHealth;
[Header("Mana")]
public int currentMana;
public int maxMana;
[Header("Defense")]
public int currentDefense;
public int maxDefense;
[Header("Attack")]
public int currentAttack;
public int maxAttack;
[Header("Attack Speed")]
public float currentAttackSpeed;
public float maxAttackSpeed;
[Header("Critical")]
public int currentCritical;
public int maxCritical;
[Header("Life Steal")]
public float currentLifeSteal;
public float maxLifeSteal;
[Header("Range")]
public float currentRange;
public float maxRange;
[Header("Elemental Mastery")]
public float currentElementalMastery;
public float maxElementalMastery;
[Header("Cooldown")]
public float currentCooldown;
public float maxCooldown;
[Header("Knockback")]
public float currentKnockback;
public float maxKnockback;
[Header("Speed")]
public float currentSpeed;
public float maxSpeed;
[Header("Recovery")]
public float currentRecovery;
public float maxRecovery;
[Header("Evade")]
public float currentEvade;
public float maxEvade;
[Header("Fortune")]
public float currentFortune;
public float maxFortune;
[Header("Character and Stat Panel")]
public Character character;
public StatPanel statPanel;
public PlayerSkill playerSkill;
public Inventory inventory;
public EquipmentPanel equipmentPanel;
[Header("Hurt Effect")]
[SerializeField] private GameObject hurtParticlePrefab;
[SerializeField]
private PlayerDamageIndicator damageIndicatorScript; // Reference to the PlayerDamageIndicator script
public PlayerLevelUpText levelUpTextScript; // Reference to the PlayerLevelUpText script
#endregion
private float lastDamageTime = 0f; // Track the time of the last damage taken or mana used
private float lastRecoveryTime = 0f;
private bool hasEquippedItemRecently = false;
private float timeSinceEquippingItem = 0f;
private float equipItemRecoveryDelay = 30f;
[Header("Player Camera")]
public Camera playerCamera; // Assign the player's camera directly in the inspector
[Header("Button Assignment")]
public float attackRange = 2f;
public LayerMask mobsLayer; // Specify the layer for "Mobs"
[SerializeField] private bool displayGizmo = true; // Toggle to display Gizmo
// Event to notify UI that stats have changed
public Action OnStatsChanged { get; set; }
private void OnDrawGizmos()
{
if (displayGizmo)
{
Gizmos.color = Color.green;
Gizmos.DrawWireSphere(transform.position, attackRange);
}
}
// Method to update the player's name
public void UpdatePlayerName(string newName)
{
PlayerName = newName;
}
#region Take Damage & Respawn
code
public void TakeDamage(int damage)
{
// Spawn the hurt particle effect if the prefab is assigned
if (hurtParticlePrefab != null)
{
GameObject hurtParticle = Instantiate(hurtParticlePrefab, transform.position, Quaternion.identity);
Destroy(hurtParticle, 0.45f); // Destroy the particle effect after 0.45 seconds
}
// Call the ShowDamageText method from PlayerDamageIndicator script and pass the damage value
if (damageIndicatorScript != null)
{
damageIndicatorScript.ShowDamageText(damage);
}
// Check if the player can evade
if (UnityEngine.Random.Range(0f, 100f) <= currentEvade)
{
Debug.Log($"{PlayerName} Evaded the Attack & Avoided {damage} Damage!");
}
else
{
// Calculate actual damage after considering defense
int actualDamage = Mathf.Max(0, damage - currentDefense);
// Damage defense first if there's any
if (currentDefense > 0)
{
int defenseDamage = Mathf.Max(0, damage - actualDamage);
currentDefense = Mathf.Max(0, currentDefense - damage);
// Log damage taken to defense if defense is greater than 0
if (defenseDamage > 0)
{
Debug.Log($"{PlayerName} Defense took {defenseDamage} damage!");
}
}
// If defense is reduced to 0, or no defense, damage health
if (currentDefense == 0)
{
int healthDamage = actualDamage;
currentHealth -= healthDamage;
// Log the health damage
Debug.Log($"{PlayerName} took {healthDamage} damage to health!");
// Check if health reaches 0
if (currentHealth <= 0)
{
Debug.Log($"{PlayerName} Died!");
// Respawn the player at the saved location and restore all stats to full
LoadPlayerData(PlayerName); // Respawn the player using saved data
RespawnPlayer();
}
}
}
// Update the last damage time to trigger recovery
lastDamageTime = Time.time;
}
private void RespawnPlayer()
{
// Restore all stats to full
SetCurrentStatsToMax(); // Reset current stats to their maximum values
// Teleport the player back to the saved location using the PlayerSaveLocation script
PlayerSaveLocation saveLocationScript = GetComponent<PlayerSaveLocation>();
if (saveLocationScript != null)
{
saveLocationScript.TeleportToSavedLocation();
}
}
#endregion
#region Start And Update
void Start()
{
// Construct the base directory path
code
SetStartingStats(); // Call this method to set starting stats
InitializeStats();
SetCurrentStatsToMax();
// Set the initial values for level and experience
PlayerLevel = 1;
CurrentEXP = 0;
ExpToLevelUp = 250;
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA", PlayerName);
// Check if the player's directory exists
if (Directory.Exists(baseDirectory))
{
// Construct the full file path for the player's data file
string filePath = Path.Combine(baseDirectory, $"{PlayerName}_Data.sav");
// Check if the player's data file exists
if (File.Exists(filePath))
{
// Load player data from file
LoadPlayerData(PlayerName);
}
}
}
private void Update()
{
// This Bellow When An Item Is Equipped It Will Update The Stats on Both The UI And The Player
UpdateMaxStats();
// Check if enough time has passed since the last damage or mana/defense depletion
if (!hasEquippedItemRecently && Time.time - lastDamageTime >= 30f)
{
// Increment current health, mana, and defense towards their maximum values over time
if (Time.time - lastRecoveryTime >= 5f) // Check if 5 seconds have passed since last recovery
{
// Increment stats by maxRecovery amount
currentHealth = Mathf.Min(maxHealth, currentHealth + Mathf.RoundToInt(maxRecovery));
currentMana = Mathf.Min(maxMana, currentMana + Mathf.RoundToInt(maxRecovery));
currentDefense = Mathf.Min(maxDefense, currentDefense + Mathf.RoundToInt(maxRecovery));
// Update the last recovery time
lastRecoveryTime = Time.time;
}
}
// Update the time since equipping an item
if (hasEquippedItemRecently)
{
timeSinceEquippingItem += Time.deltaTime;
if (timeSinceEquippingItem >= equipItemRecoveryDelay)
{
// Enough time has passed after equipping an item, reset the flag and trigger recovery
hasEquippedItemRecently = false;
lastDamageTime = Time.time;
}
}
}
#endregion
#region Level Up
public void LevelUp()
{
// Call the LevelUpText method from PlayerLevelUpText script
if (levelUpTextScript != null)
{
levelUpTextScript.ShowLevelUpText();
}
code
PlayerLevel++;
CurrentEXP -= ExpToLevelUp;
ExpToLevelUp *= 2;
// Update character stats
character.Health.BaseValue += 5 * PlayerLevel;
character.Mana.BaseValue += 2 * PlayerLevel;
character.Defence.BaseValue += 1 * PlayerLevel;
character.Attack.BaseValue += 1 * PlayerLevel;
character.AttackSpeed.BaseValue += 0.008f * PlayerLevel;
character.Critical.BaseValue += 0.05F * PlayerLevel;
character.LifeSteal.BaseValue += 0.5f * PlayerLevel;
character.Range.BaseValue += 0.015f * PlayerLevel;
character.ElementalMastery.BaseValue += 0.13f * PlayerLevel;
character.Cooldown.BaseValue += 0.1f * PlayerLevel;
character.Knockback.BaseValue += 0.025f * PlayerLevel;
character.Speed.BaseValue += 0.005f * PlayerLevel;
character.Recovery.BaseValue += 0.5f * PlayerLevel;
character.Evade.BaseValue += 0.01f * PlayerLevel;
character.Fortune.BaseValue += 0.015f * PlayerLevel;
// Update stat values
character.UpdateStatValues();
// Update max stats
UpdateMaxStats();
// Set current stats to max
SetCurrentStatsToMax();
// Show updated stats on UI
statPanel.SetStats(character.Health, character.Mana, character.Defence, character.Attack , character.AttackSpeed, character.Critical, character.LifeSteal, character.Range, character.ElementalMastery, character.Speed, character.Cooldown, character.Knockback, character.Recovery, character.Evade, character.Fortune);
}
#endregion
private void SetStartingStats()
{
// Set starting stats for the player based on character stats
currentHealth = (int)character.Health.Value;
maxHealth = (int)character.Health.Value;
currentMana = (int)character.Mana.Value;
maxMana = (int)character.Mana.Value;
currentDefense = (int)character.Defence.Value;
maxDefense = (int)character.Defence.Value;
currentAttack = (int)character.Attack.Value;
maxAttack = (int)character.Attack.Value;
currentAttackSpeed = character.AttackSpeed.Value;
maxAttackSpeed = character.AttackSpeed.Value;
currentCritical = (int)character.Critical.Value;
maxCritical = (int)character.Critical.Value;
currentLifeSteal = character.LifeSteal.Value;
maxLifeSteal = character.LifeSteal.Value;
currentRange = character.Range.Value;
maxRange = character.Range.Value;
currentElementalMastery = character.ElementalMastery.Value;
maxElementalMastery = character.ElementalMastery.Value;
currentSpeed = character.Speed.Value;
maxSpeed = character.Speed.Value;
currentCooldown = character.Cooldown.Value;
maxCooldown = character.Cooldown.Value;
currentKnockback = character.Knockback.Value;
maxKnockback = character.Knockback.Value;
currentRecovery = character.Recovery.Value;
maxRecovery = character.Recovery.Value;
currentEvade = character.Evade.Value;
maxEvade = character.Evade.Value;
currentFortune = character.Fortune.Value;
maxFortune = character.Fortune.Value;
// Call UpdateStatValues to apply the changes
character.UpdateStatValues();
// Update max and current stats
UpdateMaxStats();
SetCurrentStatsToMax();
}
// Update the maximum stats of the character
public void UpdateMaxStats()
{
// Update max stats for the player based on character stats
maxHealth = (int)character.Health.Value;
maxMana = (int)character.Mana.Value;
maxDefense = (int)character.Defence.Value;
maxAttack = (int)character.Attack.Value;
maxAttackSpeed = character.AttackSpeed.Value;
maxCritical = (int)character.Critical.Value;
maxLifeSteal = character.LifeSteal.Value;
maxRange = character.Range.Value;
maxElementalMastery = character.ElementalMastery.Value;
maxSpeed = character.Speed.Value;
maxCooldown = character.Cooldown.Value;
maxKnockback = character.Knockback.Value;
maxRecovery = character.Recovery.Value;
maxEvade = character.Evade.Value;
maxFortune = character.Fortune.Value;
}
// Check if any current stats have changed due to equipping items
public void CurrentStatsChange()
{
// Mark that an item has been equipped recently
hasEquippedItemRecently = true;
timeSinceEquippingItem = 0f;
}
public void InitializeStats()
{
// Update max stats
UpdateMaxStats();
// Initialize current stats
maxHealth = Mathf.RoundToInt(character.Health.Value);
currentHealth = maxHealth;
maxMana = Mathf.RoundToInt(character.Mana.Value);
currentMana = maxMana;
maxDefense = Mathf.RoundToInt(character.Defence.Value);
currentDefense = maxDefense;
maxAttack = Mathf.RoundToInt(character.Attack.Value);
currentAttack = maxAttack;
maxAttackSpeed = character.AttackSpeed.Value;
currentAttackSpeed = maxAttackSpeed;
maxCritical = Mathf.RoundToInt(character.Critical.Value);
currentCritical = maxCritical;
maxLifeSteal = Mathf.RoundToInt(character.LifeSteal.Value);
currentLifeSteal = maxLifeSteal;
maxRange = Mathf.RoundToInt(character.Range.Value);
currentRange = maxRange;
maxElementalMastery = Mathf.RoundToInt(character.ElementalMastery.Value);
currentElementalMastery = maxElementalMastery;
maxSpeed = Mathf.RoundToInt(character.Speed.Value);
currentSpeed = maxSpeed;
maxCooldown = character.Cooldown.Value;
currentCooldown = maxCooldown;
maxKnockback = Mathf.RoundToInt(character.Knockback.Value);
currentKnockback = maxKnockback;
maxRecovery = character.Recovery.Value;
currentRecovery = maxRecovery;
maxEvade = character.Evade.Value;
currentEvade = maxEvade;
maxFortune = Mathf.RoundToInt(character.Fortune.Value);
currentFortune = maxFortune;
// Replace UpdateCurrentStats with the appropriate method
// (e.g., SetCurrentStatsToMax or any other method that updates your current stats)
SetCurrentStatsToMax();
}
public void SetCurrentStatsToMax()
{
currentHealth = maxHealth;
currentMana = maxMana;
currentDefense = maxDefense;
currentAttack = maxAttack;
currentAttackSpeed = maxAttackSpeed;
currentCritical = maxCritical;
currentLifeSteal = maxLifeSteal;
currentRange = maxRange;
currentElementalMastery = maxElementalMastery;
currentCooldown = maxCooldown;
currentKnockback = maxKnockback;
currentSpeed = maxSpeed;
currentRecovery = maxRecovery;
currentEvade = maxEvade;
currentFortune = maxFortune;
// Reset the last recovery time to prevent immediate recovery
lastRecoveryTime = Time.time;
}
public void AdjustStatsIfNeeded()
{
// Health
int newMaxHealth = Mathf.RoundToInt(character.Health.Value);
if (newMaxHealth < currentHealth)
{
currentHealth = newMaxHealth;
}
// Mana
int newMaxMana = Mathf.RoundToInt(character.Mana.Value);
if (newMaxMana < currentMana)
{
currentMana = newMaxMana;
}
// Defense
int newMaxDefense = Mathf.RoundToInt(character.Defence.Value);
if (newMaxDefense < currentDefense)
{
currentDefense = newMaxDefense;
}
// Attack
int newMaxAttack = Mathf.RoundToInt(character.Attack.Value);
if (newMaxAttack < currentAttack)
{
currentAttack = newMaxAttack;
}
// Attack Speed
float newMaxAttackSpeed = character.AttackSpeed.Value;
if (newMaxAttackSpeed < currentAttackSpeed)
{
currentAttackSpeed = newMaxAttackSpeed;
}
// Critical
int newMaxCritical = Mathf.RoundToInt(character.Critical.Value);
if (newMaxCritical < currentCritical)
{
currentCritical = newMaxCritical;
}
// LifeSteal
int newMaxLifeSteal = Mathf.RoundToInt(character.LifeSteal.Value);
if (newMaxLifeSteal < currentLifeSteal)
{
currentLifeSteal = newMaxLifeSteal;
}
// Range
int newMaxRange = Mathf.RoundToInt(character.Range.Value);
if (newMaxRange < currentRange)
{
currentRange = newMaxRange;
}
// ElementalMastery
int newMaxElementalMastery = Mathf.RoundToInt(character.ElementalMastery.Value);
if (newMaxElementalMastery < currentElementalMastery)
{
currentElementalMastery = newMaxElementalMastery;
}
// Speed
float newMaxSpeed = character.Speed.Value;
if (newMaxSpeed < currentSpeed)
{
currentSpeed = newMaxSpeed;
}
// Cooldown
float newMaxCooldown = character.Cooldown.Value;
if (newMaxCooldown < currentCooldown)
{
currentCooldown = newMaxCooldown;
}
// Knockback
int newMaxKnockback = Mathf.RoundToInt(character.Knockback.Value);
if (newMaxKnockback < currentKnockback)
{
currentKnockback = newMaxKnockback;
}
// Recovery
float newMaxRecovery = character.Recovery.Value;
if (newMaxRecovery < currentRecovery)
{
currentRecovery = newMaxRecovery;
}
// Evade
float newMaxEvade = character.Evade.Value;
if (newMaxEvade < currentEvade)
{
currentEvade = newMaxEvade;
}
// Fortune
int newMaxFortune = Mathf.RoundToInt(character.Fortune.Value);
if (newMaxFortune < currentFortune)
{
currentFortune = newMaxFortune;
}
CurrentStatsChange();
}
public void IncreaseExperience(int amount)
{
CurrentEXP += amount;
while (CurrentEXP >= ExpToLevelUp)
{
LevelUp();
}
}
public void AddStats(int healthToAdd, int defenseToAdd, int manaToAdd)
{
// Check if adding health would exceed the maximum
if (currentHealth < maxHealth)
{
// Calculate the new health after adding
int newHealth = currentHealth + healthToAdd;
// Ensure the new health doesn't exceed the maximum
newHealth = Mathf.Clamp(newHealth, 0, maxHealth);
// If the new health is different from the current health, apply the change
if (newHealth != currentHealth)
{
currentHealth = newHealth;
CurrentStatsChange(); // Notify stats change if needed
}
}
// Check if adding defense would exceed the maximum
if (currentDefense < maxDefense)
{
// Calculate the new defense after adding
int newDefense = currentDefense + defenseToAdd;
// Ensure the new defense doesn't exceed the maximum
newDefense = Mathf.Clamp(newDefense, 0, maxDefense);
// If the new defense is different from the current defense, apply the change
if (newDefense != currentDefense)
{
currentDefense = newDefense;
CurrentStatsChange(); // Notify stats change if needed
}
}
// Check if adding mana would exceed the maximum
if (currentMana < maxMana)
{
// Calculate the new mana after adding
int newMana = currentMana + manaToAdd;
// Ensure the new mana doesn't exceed the maximum
newMana = Mathf.Clamp(newMana, 0, maxMana);
// If the new mana is different from the current mana, apply the change
if (newMana != currentMana)
{
currentMana = newMana;
CurrentStatsChange(); // Notify stats change if needed
}
}
}
// This allows the UsableItem to start coroutines on the player
public new Coroutine StartCoroutine(IEnumerator routine)
{
return base.StartCoroutine(routine);
}
#region Save And Load System
code
public void SavePlayerData()
{
// Create a PlayerData object and populate it with current player state
PlayerData data = new PlayerData();
data.playerName = PlayerName;
data.playerLevel = PlayerLevel;
data.currentEXP = CurrentEXP;
data.expToLevelUp = ExpToLevelUp;
data.currentHealth = currentHealth;
data.maxHealth = maxHealth;
data.currentMana = currentMana;
data.maxMana = maxMana;
data.currentDefense = currentDefense;
data.maxDefense = maxDefense;
data.currentAttack = currentAttack;
data.maxAttack = maxAttack;
data.currentAttackSpeed = currentAttackSpeed;
data.maxAttackSpeed = maxAttackSpeed;
data.currentCritical = currentCritical;
data.maxCritical = maxCritical;
data.currentLifeSteal = currentLifeSteal;
data.maxLifeSteal = maxLifeSteal;
data.currentRange = currentRange;
data.maxRange = maxRange;
data.currentElementalMastery = currentElementalMastery;
data.maxElementalMastery = maxElementalMastery;
data.currentSpeed = currentSpeed;
data.maxSpeed = maxSpeed;
data.currentCooldown = currentCooldown;
data.maxCooldown = maxCooldown;
data.currentKnockback = currentKnockback;
data.maxKnockback = maxKnockback;
data.currentRecovery = currentRecovery;
data.maxRecovery = maxRecovery;
data.currentEvade = currentEvade;
data.maxEvade = maxEvade;
data.currentFortune = currentFortune;
data.maxFortune = maxFortune;
data.playerPosX = transform.position.x;
data.playerPosY = transform.position.y;
data.playerPosZ = transform.position.z;
// Adjusted file path
string saveDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA", PlayerName);
string fileName = $"{PlayerName}_Data.sav"; // Adjusted file name here
string savePath = Path.Combine(saveDirectory, fileName);
try
{
// Create directory if it doesn't exist
Directory.CreateDirectory(saveDirectory);
using (FileStream fileStream = new FileStream(savePath, FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fileStream, data);
}
Debug.Log($"<color=#ADD8E6><b>Player data saved successfully</b></color> to: {savePath}");
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to save player data: {e.Message}</b></color>");
}
}
public void LoadPlayerData(string playerName)
{
// Construct the base directory path
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
code
// Check if the base directory exists
if (!Directory.Exists(baseDirectory))
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
return;
}
// Append the player's folder based on PlayerName
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
// Ensure the player's directory exists
if (!Directory.Exists(playerDirectory))
{
Debug.LogWarning($"<color=red><b>No saved data found for player: {PlayerName}</b></color>");
return;
}
// Construct the full file path
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
// Check if the file exists
if (File.Exists(filePath))
{
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = formatter.Deserialize(fileStream) as PlayerData;
// Assign loaded data back to the player (optional, depends on your game's logic)
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
currentHealth = data.currentHealth;
maxHealth = data.maxHealth;
currentMana = data.currentMana;
maxMana = data.maxMana;
currentDefense = data.currentDefense;
maxDefense = data.maxDefense;
currentAttack = data.currentAttack;
maxAttack = data.maxAttack;
currentAttackSpeed = data.currentAttackSpeed;
maxAttackSpeed = data.maxAttackSpeed;
currentCritical = data.currentCritical;
maxCritical = data.maxCritical;
currentLifeSteal = data.currentLifeSteal;
maxLifeSteal = data.maxLifeSteal;
currentRange = data.currentRange;
maxRange = data.maxRange;
currentElementalMastery = data.currentElementalMastery;
maxElementalMastery = data.maxElementalMastery;
currentSpeed = data.currentSpeed;
maxSpeed = data.maxSpeed;
currentCooldown = data.currentCooldown;
maxCooldown = data.maxCooldown;
currentKnockback = data.currentKnockback;
maxKnockback = data.maxKnockback;
currentRecovery = data.currentRecovery;
maxRecovery = data.maxRecovery;
currentEvade = data.currentEvade;
maxEvade = data.maxEvade;
currentFortune = data.currentFortune;
maxFortune = data.maxFortune;
// Assuming 'character' is an instance of the Character class
character.LoadStatsFromData(data);
playerSkill.LoadSkillData(PlayerName);
// Position (example)
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
Debug.Log($"<color=#00FF00><b>Loaded PlayerData</b></color>");
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
else
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
}
}
#endregion
}
i need to fix this current stats and max stats of player.cs script when loadig and updating stats something is incorrect meaning we are loading characters stat values , when we should be loading players max values as our max values and cracters values as our current values
public void LoadPlayerData(string playerName)
{
// Construct the base directory path
string baseDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "World Of Normies", "SAVE DATA");
// Append the player's specific directory
string playerDirectory = Path.Combine(baseDirectory, PlayerName);
// Check if the player's directory exists
if (!Directory.Exists(playerDirectory))
{
Debug.LogWarning($"<color=red><b>No saved data found for player: {PlayerName}</b></color>");
return;
}
// Define the full file path
string filePath = Path.Combine(playerDirectory, $"{PlayerName}_Data.sav");
// Check if the file exists
if (!File.Exists(filePath))
{
Debug.LogWarning("<color=red><b>No saved player data found.</b></color>");
return;
}
// Begin the deserialization process
BinaryFormatter formatter = new BinaryFormatter();
try
{
using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
PlayerData data = formatter.Deserialize(fileStream) as PlayerData;
// Load player base info
PlayerName = data.playerName;
PlayerLevel = data.playerLevel;
CurrentEXP = data.currentEXP;
ExpToLevelUp = data.expToLevelUp;
// Load current (temporary state) and max (potential) stats
currentHealth = data.currentHealth;
currentMana = data.currentMana;
currentDefense = data.currentDefense;
currentAttack = data.currentAttack;
currentAttackSpeed = data.currentAttackSpeed;
currentCritical = data.currentCritical;
currentLifeSteal = data.currentLifeSteal;
currentRange = data.currentRange;
currentElementalMastery = data.currentElementalMastery;
currentSpeed = data.currentSpeed;
currentCooldown = data.currentCooldown;
currentKnockback = data.currentKnockback;
currentRecovery = data.currentRecovery;
currentEvade = data.currentEvade;
currentFortune = data.currentFortune;
// Set max values directly from stored data
maxHealth = data.maxHealth;
maxMana = data.maxMana;
maxDefense = data.maxDefense;
maxAttack = data.maxAttack;
maxAttackSpeed = data.maxAttackSpeed;
maxCritical = data.maxCritical;
maxLifeSteal = data.maxLifeSteal;
maxRange = data.maxRange;
maxElementalMastery = data.maxElementalMastery;
maxSpeed = data.maxSpeed;
maxCooldown = data.maxCooldown;
maxKnockback = data.maxKnockback;
maxRecovery = data.maxRecovery;
maxEvade = data.maxEvade;
maxFortune = data.maxFortune;
// Ensure character archetype or modifications are aligned with base or current implementations
character.LoadStatsFromData(data);
// Specifics such as skills or special settings
playerSkill.LoadSkillData(PlayerName);
// Re-establish player position
Vector3 playerPosition = new Vector3(data.playerPosX, data.playerPosY, data.playerPosZ);
transform.position = playerPosition;
// Log successful loading
Debug.Log($"<color=#00FF00><b>Loaded PlayerData</b></color>");
}
}
catch (Exception e)
{
Debug.LogError($"<color=red><b>Failed to load player data: {e.Message}</b></color>");
}
}
Considerations:
Stat Synchronization: After loading, consider synchronization points where game events might adjust stats (e.g., debuffs, skills, mods).
Debug Statements: Implement debug statements especially around loading and setting max/current values to quickly trace unexpected behaviors.
Verify Dependencies: Ensure methods like LoadStatsFromData on Character and LoadSkillData function consistently with intended behavior as parts of your loading logic.
This overall structure ensures that the player's state is restored as accurately as possible from the saved data. The data reflects current gameplay realities alongside max values derived from character-based calculations and should align them as needed for gameplay. If further issues arise, inspect lifecycle events or other systems interacting post-load that might inadvertently adjust these values.