Forum begins after the advertisement:


[Part 8] How to let each health and mana orbs call once only in the game

Home Forums Video Game Tutorial Series Creating a Metroidvania in Unity [Part 8] How to let each health and mana orbs call once only in the game

Viewing 15 posts - 16 through 30 (of 46 total)
  • Author
    Posts
  • #14995
    Elvin Sim
    Participant
    #14996
    Joseph Tang
    Moderator
    Helpful?
    Up
    0
    ::

    To be sure, is anything setting, such as your pickup’s scripts [Not the pickupmanager.cs, but the incerase heart shard/ mana orb scripts] calling the GameManager’s TriggerPickupInteract() as per point [2] of the previous post?

    #14997
    Elvin Sim
    Participant
    Helpful?
    Up
    0
    ::
    public class IncreaseMaxHealth : MonoBehaviour
    {
        [SerializeField] GameObject particles;
        [SerializeField] GameObject canvasUI;
    
        [SerializeField] HeartShards heartShards;
    
        bool used;
    
        // Start is called before the first frame update
        void Start()
        {
            if (PlayerController.Instance.maxHealth >= PlayerController.Instance.maxTotalHealth)
            {
                Destroy(gameObject);
            }
        }
    
        private void OnTriggerEnter2D(Collider2D _collision)
        {
            if (_collision.CompareTag("Player") && !used)
            {
                used = true;
                StartCoroutine(ShowUI());
            }
        }
    
        IEnumerator ShowUI()
        {
            GameObject _particles = Instantiate(particles, transform.position, Quaternion.identity);
            Destroy(_particles, 0.5f);
            yield return new WaitForSeconds(0.5f);
    
            canvasUI.SetActive(true);
            heartShards.initialFillAmount = PlayerController.Instance.heartShards * 0.25f;
            PlayerController.Instance.heartShards++;
            heartShards.targetFillAmount = PlayerController.Instance.heartShards * 0.25f;
    
            StartCoroutine(heartShards.LerpFill());
    
            yield return new WaitForSeconds(2.5f);
            SaveData.Instance.SavePlayerData();
            canvasUI.SetActive(false);
            Destroy(gameObject);
        }
    }
    #14998
    Elvin Sim
    Participant
    Helpful?
    Up
    0
    ::

    I think no

    #15003
    Joseph Tang
    Moderator
    Helpful?
    Up
    0
    ::
    public class IncreaseMaxHealth : MonoBehaviour
    {
        ...
    
        private void OnTriggerEnter2D(Collider2D _collision)
        {
            if (_collision.CompareTag("Player") && !used)
            {
                GameManager.Instance.TriggerPickupInteract(gameObject.name)
                used = true;
                StartCoroutine(ShowUI());
            }
        }
    
        ...
    }
    #15006
    Elvin Sim
    Participant
    #15007
    Elvin Sim
    Participant
    Helpful?
    Up
    0
    ::

    Translate to another scene and come back is ok, but when I exit the game and load again it doesn’t work

    #15008
    Joseph Tang
    Moderator
    Helpful?
    Up
    0
    ::

    Likely because nothing is calling LoadAndDeactivateInteractedObjects() at the beginning of a scene except for the PickupManager.cs script on start or if you are entering the scene with the PlayerController.cs.

    This should be solved by adding a destroy in main menu script onto the PickUpManager game object, like the ones you have on your player, canvas and game manager prefabs.

    #15009
    Elvin Sim
    Participant
    Helpful?
    Up
    0
    ::

    still same

    View post on imgur.com

    #15010
    Elvin Sim
    Participant
    Helpful?
    Up
    0
    ::
    public struct SaveData
    {
        public static SaveData Instance;
    
        //map stuff
        public HashSet<string> sceneNames;
    
        //bench stuff
        public string benchSceneName;
        public Vector2 benchPos;
    
        //player stuff
        public int playerHealth;
        public int playerMaxHealth;
        public int playerHeartShards;
        public float playerMana;
        public int playerManaOrbs;
        public int playerOrbShard;
        public float playerOrb0fill, playerOrb1fill, playerOrb2fill;
        public bool playerHalfMana;
        public Vector2 playerPosition;
        public string lastScene;
    
        public bool playerUnlockedWallJump, playerUnlockedDash, playerUnlockedVarJump;
        public bool playerUnlockedSideCast, playerUnlockedUpCast, playerUnlockedDownCast;
       
        //enemies stuff
        //shade
        public Vector2 shadePos;
        public string sceneWithShade;
        public Quaternion shadeRot;
    
        //The Hollow Knight
        public bool THKDefeated;
    
        // Pickups and Chests data
        public HashSet<string> collectedPickups; // HashSet to store collected pickups
    
        public void Initialize()
        {
            if(!File.Exists(Application.persistentDataPath + "/save.scenes.data"))
            {
                using (BinaryWriter writer = new BinaryWriter(File.Create(Application.persistentDataPath + "/save.scenes.data")))
                {
                    writer.Write(0); // Write an empty scene data structure
                }
            }
    
            // Load existing data
            LoadSceneData();
    
            if (!File.Exists(Application.persistentDataPath + "/save.bench.data")) 
            {
                BinaryWriter writer = new BinaryWriter(File.Create(Application.persistentDataPath + "/save.bench.data"));
            }
    
            if (!File.Exists(Application.persistentDataPath + "/save.player.data"))
            {
                BinaryWriter writer = new BinaryWriter(File.Create(Application.persistentDataPath + "/save.player.data"));
            }
    
            if (!File.Exists(Application.persistentDataPath + "/save.shade.data"))
            {
                BinaryWriter writer = new BinaryWriter(File.Create(Application.persistentDataPath + "/save.shade.data"));
            }
    
            if (!File.Exists(Application.persistentDataPath + "/save.boss.data"))
            {
                BinaryWriter writer = new BinaryWriter(File.Create(Application.persistentDataPath + "/save.boss.data"));
            }
    
            if (!File.Exists(Application.persistentDataPath + "/save.pickups.data"))
            {
                BinaryWriter writer = new BinaryWriter(File.Create(Application.persistentDataPath + "/save.pickups.data"));
            }
    
            if (sceneNames == null)
            {
                sceneNames = new HashSet<string>();
            }
    
            if (collectedPickups == null)
            {
                collectedPickups = new HashSet<string>();
            }
        }
    
        #region Scenes Stuff
        public void SaveSceneData()
        {
            using (BinaryWriter writer = new BinaryWriter(File.OpenWrite(Application.persistentDataPath + "/save.scenes.data")))
            {
                writer.Write(sceneNames.Count);
                foreach (string sceneName in sceneNames)
                {
                    writer.Write(sceneName);
                }
            }
        }
    
        public void LoadSceneData()
        {
            if (File.Exists(Application.persistentDataPath + "/save.scenes.data"))
            {
                using (BinaryReader reader = new BinaryReader(File.OpenRead(Application.persistentDataPath + "/save.scenes.data")))
                {
                    int sceneCount = reader.ReadInt32();
                    sceneNames = new HashSet<string>();
                    for (int i = 0; i < sceneCount; i++)
                    {
                        string sceneName = reader.ReadString();
                        sceneNames.Add(sceneName);
                    }
                }
            }
            else
            {
                sceneNames = new HashSet<string>();
            }
        }
        #endregion
    
        #region Delete save data
        public void DeleteScenesData()
        {
            string path = Application.persistentDataPath + "/save.scenes.data";
            if (File.Exists(path))
            {
                File.Delete(path);
                Debug.Log("Scenes data deleted.");
            }
        }
    
        public void DeleteBenchData()
        {
            string path = Application.persistentDataPath + "/save.bench.data";
            if (File.Exists(path))
            {
                File.Delete(path);
                Debug.Log("Bench data deleted.");
            }
        }
    
        public void DeletePlayerData()
        {
            string path = Application.persistentDataPath + "/save.player.data";
            if (File.Exists(path))
            {
                File.Delete(path);
                Debug.Log("Player save data deleted.");
            }
        }
    
        public void DeleteShadeData()
        {
            string path = Application.persistentDataPath + "/save.shade.data";
            if (File.Exists(path))
            {
                File.Delete(path);
                Debug.Log("Shade save data deleted.");
            }
        }
    
        public void DeleteBossData()
        {
            string path = Application.persistentDataPath + "/save.boss.data";
            if (File.Exists(path))
            {
                File.Delete(path);
                Debug.Log("Boss save data deleted.");
            }
        }
    
        public void DeleteAllSaveData()
        {
            DeleteScenesData();
            DeleteBenchData();
            DeletePlayerData();
            DeleteShadeData();
            DeleteBossData();
        }
    
        #endregion
    
        #region Bench Stuff
        public void SaveBench()
        {
            using (BinaryWriter writer = new BinaryWriter(File.OpenWrite(Application.persistentDataPath + "/save.bench.data")))
            {
                writer.Write(benchSceneName);
                writer.Write(benchPos.x);
                writer.Write(benchPos.y);
            }
        }
    
        public void LoadBench()
        {
            string savePath = Application.persistentDataPath + "/save.bench.data";
            if (File.Exists(savePath) && new FileInfo(savePath).Length > 0)
            {
                using(BinaryReader reader = new BinaryReader(File.OpenRead(Application.persistentDataPath + "/save.bench.data")))
                {
                    benchSceneName = reader.ReadString();
                    benchPos.x = reader.ReadSingle();
                    benchPos.y = reader.ReadSingle();
                }
            }
            else
            {
                Debug.Log("Bench doesn't exist");
            }
        }
        #endregion
    
        #region Player Stuff
        public void SavePlayerData()
        {
            using (BinaryWriter writer = new BinaryWriter(File.OpenWrite(Application.persistentDataPath + "/save.player.data")))
            {
                playerHealth = PlayerController.Instance.Health;
                writer.Write(playerHealth);
                playerMaxHealth = PlayerController.Instance.maxHealth;
                writer.Write(playerMaxHealth);
                playerHeartShards = PlayerController.Instance.heartShards;
                writer.Write(playerHeartShards);
    
                playerMana = PlayerController.Instance.Mana;
                writer.Write(playerMana);
                playerHalfMana = PlayerController.Instance.halfMana;
                writer.Write(playerHalfMana);
                playerManaOrbs = PlayerController.Instance.manaOrbs;
                writer.Write(playerManaOrbs);
                playerOrbShard = PlayerController.Instance.orbShard;
                writer.Write(playerOrbShard);
                playerOrb0fill = PlayerController.Instance.manaOrbsHandler.orbFills[0].fillAmount;
                writer.Write(playerOrb0fill);
                playerOrb1fill = PlayerController.Instance.manaOrbsHandler.orbFills[1].fillAmount;
                writer.Write(playerOrb1fill);
                playerOrb2fill = PlayerController.Instance.manaOrbsHandler.orbFills[2].fillAmount;
                writer.Write(playerOrb2fill);
    
                playerUnlockedWallJump = PlayerController.Instance.unlockedWallJump;
                writer.Write(playerUnlockedWallJump);
                playerUnlockedDash = PlayerController.Instance.unlockedDash;
                writer.Write(playerUnlockedDash);
                playerUnlockedVarJump = PlayerController.Instance.unlockedVarJump;
                writer.Write(playerUnlockedVarJump);
    
                playerUnlockedSideCast = PlayerController.Instance.unlockedSideCast;
                writer.Write(playerUnlockedSideCast);
                playerUnlockedUpCast = PlayerController.Instance.unlockedUpCast;
                writer.Write(playerUnlockedUpCast);
                playerUnlockedDownCast = PlayerController.Instance.unlockedDownCast;
                writer.Write(playerUnlockedDownCast);
                
    
                playerPosition = PlayerController.Instance.transform.position;
                writer.Write(playerPosition.x);
                writer.Write(playerPosition.y);
    
                lastScene = SceneManager.GetActiveScene().name;
                writer.Write(lastScene);
    
            }
            Debug.Log("saved player data");
        }
    
        public void LoadPlayerData()
        {
            string savePath = Application.persistentDataPath + "/save.player.data";
            if (File.Exists(savePath) && new FileInfo(savePath).Length > 0)
            {
                using(BinaryReader reader = new BinaryReader(File.OpenRead(Application.persistentDataPath + "/save.player.data")))
                {
                    playerHealth = reader.ReadInt32();
                    playerMaxHealth = reader.ReadInt32();
                    playerHeartShards = reader.ReadInt32();
                    playerMana = reader.ReadSingle();
                    playerHalfMana = reader.ReadBoolean();
                    playerManaOrbs = reader.ReadInt32();
                    playerOrbShard = reader.ReadInt32();
                    playerOrb0fill = reader.ReadSingle();
                    playerOrb1fill = reader.ReadSingle();
                    playerOrb2fill = reader.ReadSingle();
    
                    playerUnlockedWallJump = reader.ReadBoolean();
                    playerUnlockedDash= reader.ReadBoolean();
                    playerUnlockedVarJump= reader.ReadBoolean();
    
                    playerUnlockedSideCast= reader.ReadBoolean();
                    playerUnlockedUpCast = reader.ReadBoolean();
                    playerUnlockedDownCast = reader.ReadBoolean();
    
                    playerPosition.x = reader.ReadSingle();
                    playerPosition.y = reader.ReadSingle();
    
                    lastScene = reader.ReadString();
    
                    SceneManager.LoadScene(lastScene);
                    PlayerController.Instance.transform.position = playerPosition;
                    PlayerController.Instance.halfMana = playerHalfMana;
                    PlayerController.Instance.Health = playerHealth;
                    PlayerController.Instance.maxHealth = playerMaxHealth;
                    PlayerController.Instance.heartShards = playerHeartShards;
                    PlayerController.Instance.Mana = playerMana;
                    PlayerController.Instance.manaOrbs = playerManaOrbs;
                    PlayerController.Instance.orbShard = playerOrbShard;
                    PlayerController.Instance.manaOrbsHandler.orbFills[0].fillAmount = playerOrb0fill;
                    PlayerController.Instance.manaOrbsHandler.orbFills[1].fillAmount = playerOrb1fill;
                    PlayerController.Instance.manaOrbsHandler.orbFills[2].fillAmount = playerOrb2fill;
    
                    PlayerController.Instance.unlockedWallJump = playerUnlockedWallJump;
                    PlayerController.Instance.unlockedDash = playerUnlockedDash;
                    PlayerController.Instance.unlockedVarJump = playerUnlockedVarJump;
    
                    PlayerController.Instance.unlockedSideCast = playerUnlockedSideCast;
                    PlayerController.Instance.unlockedUpCast = playerUnlockedUpCast;
                    PlayerController.Instance.unlockedDownCast = playerUnlockedDownCast;
    
                }
                Debug.Log("load player data");
                Debug.Log(playerHalfMana);
            }
            else
            {
                Debug.Log("File doesn't exist");
                PlayerController.Instance.halfMana = false;
                PlayerController.Instance.Health = PlayerController.Instance.maxHealth;
                PlayerController.Instance.Mana = 0.5f;
                PlayerController.Instance.heartShards = 0;
    
                PlayerController.Instance.unlockedWallJump = false;
                PlayerController.Instance.unlockedDash = false;
                PlayerController.Instance.unlockedVarJump = false;
    
                PlayerController.Instance.unlockedSideCast = false;
                PlayerController.Instance.unlockedUpCast = false;
                PlayerController.Instance.unlockedDownCast = false;
    
            }
        }
        #endregion
    
        #region Shade Stuff
        public void SaveShadeData()
        {
            using(BinaryWriter writer = new BinaryWriter(File.OpenWrite(Application.persistentDataPath + "/save.shade.data")))
            {
                sceneWithShade = SceneManager.GetActiveScene().name;
                shadePos = Shade.Instance.transform.position;
                shadeRot = Shade.Instance.transform.rotation;
    
                writer.Write(sceneWithShade);
    
                writer.Write(shadePos.x);
                writer.Write(shadePos.y);
    
                writer.Write(shadeRot.x);
                writer.Write(shadeRot.y);
                writer.Write(shadeRot.z);
                writer.Write(shadeRot.w);
            }
        }
    
        public void LoadShadeData()
        {
            string savePath = Application.persistentDataPath + "/save.shade.data";
            if (File.Exists(savePath) && new FileInfo(savePath).Length > 0)
            {
                using(BinaryReader reader = new BinaryReader(File.OpenRead(Application.persistentDataPath + "/save.shade.data")))
                {
                    sceneWithShade = reader.ReadString();
                    shadePos.x = reader.ReadSingle();
                    shadePos.y = reader.ReadSingle();
    
                    float rotationX = reader.ReadSingle();
                    float rotationY = reader.ReadSingle();
                    float rotationZ = reader.ReadSingle();
                    float rotationW = reader.ReadSingle();
                    shadeRot = new Quaternion(rotationX, rotationY, rotationZ, rotationW);
                }
                Debug.Log("Load shade data");
            }
            else
            {
                Debug.Log("Shade doesn't exist");
            }
        }
        #endregion
    
        #region The Hollow Knight
        public void SaveBossData()
        {
            using (BinaryWriter writer = new BinaryWriter(File.OpenWrite(Application.persistentDataPath + "/save.boss.data")))
            {
                THKDefeated = GameManager.Instance.THKDefeated;
    
                writer.Write(THKDefeated);
            }
        }
    
        public void LoadBossData()
        {
            string savePath = Application.persistentDataPath + "/save.boss.data";
            if (File.Exists(savePath) && new FileInfo(savePath).Length > 0)
            {
                using (BinaryReader reader = new BinaryReader(File.OpenRead(Application.persistentDataPath + "/save.boss.data")))
                {
                    THKDefeated = reader.ReadBoolean();
    
                    GameManager.Instance.THKDefeated = THKDefeated;
                }
            }
            else
            {
                Debug.Log("Boss doesnt exist");
            }
        }
        #endregion
    
     
        #region Orbs Save Data
        public void AddCollectedPickup(string pickupID)
        {
            // Add pickup ID to collected pickups
            collectedPickups.Add(pickupID);
            SavePickups();
        }
    
        public void SavePickups()
        {
            using (BinaryWriter writer = new BinaryWriter(File.OpenWrite(Application.persistentDataPath + "/save.pickups.data")))
            {
                // Save collected pickups
                writer.Write(collectedPickups.Count);
                foreach (string pickupID in collectedPickups)
                {
                    writer.Write(pickupID);
                }
            }
        }
    
        public void LoadPickups()
        {
            string savePath = Application.persistentDataPath + "/save.pickups.data";
            if (File.Exists(savePath) && new FileInfo(savePath).Length > 0)
            {
                using (BinaryReader reader = new BinaryReader(File.OpenRead(Application.persistentDataPath + "/save.pickups.data")))
                {
                    // Load collected pickups
                    int numCollectedPickups = reader.ReadInt32();
                    for (int i = 0; i < numCollectedPickups; i++)
                    {
                        collectedPickups.Add(reader.ReadString());
                    }
                }
            }
        }
        #endregion
    #15011
    Elvin Sim
    Participant
    Helpful?
    Up
    0
    ::

    And I think is the loadPickup doesn’t mention? you can see it is zero reference

    View post on imgur.com

    #15013
    Elvin Sim
    Participant
    Helpful?
    Up
    0
    ::

    Sorry for bother, but if you can help me ASAP I am very appreciate, not rushing you guys, just because I need to pass up my assignment after a few days, so I am little rushing

    #15017
    Elvin Sim
    Participant
    Helpful?
    Up
    0
    ::
    public class PickupManager : MonoBehaviour
    {
        public static PickupManager Instance;
    
        private void Awake()
        {
            if(Instance != null && Instance != this)
            {
                Destroy(gameObject);
            }
            else
            {
                Instance = this;
            }
    
            DontDestroyOnLoad(gameObject);
        }
    
        // Start is called before the first frame update
        void Start()
        {
            LoadAndDeactivateInteractedObjects(); // Load saved data and deactivate pickups
        }
    
        public void LoadAndDeactivateInteractedObjects()
        {
            HashSet<string> collectedPickups = SaveData.Instance.collectedPickups;
            print("Called");
    
            // Deactivate pickups that have been collected
            foreach (GameObject pickup in GameObject.FindGameObjectsWithTag("Pickup"))
            {
                string pickupID = pickup.name; // Assuming the name of the object is its ID
    
                print(pickupID);
    
                if (collectedPickups.Contains(pickupID))
                {
                    print("found");
                    pickup.SetActive(false); // Deactivate the pickup
                    print("deactivated");
                }
            }
        }
    }
    #15018
    Elvin Sim
    Participant
    Helpful?
    Up
    0
    ::
    public class GameManager : MonoBehaviour
    {
        public string transitionedFromScene;
    
        public Vector2 platformingRespawnPoint;
        public Vector2 respawnPoint;
        [SerializeField] Bench bench;
    
        public GameObject shade;
    
        public bool THKDefeated = false;
    
        [SerializeField] private FadeUI pauseMenu;
        [SerializeField] private float fadeTime;
        public bool gameIsPaused;
    
        public static GameManager Instance {  get; private set; }
        private void Awake()
        {
            SaveData.Instance.Initialize();
            if(Instance != null && Instance != this)
            {
                Destroy(gameObject);
            }
            else
            {
                Instance = this;
            }
    
            if(PlayerController.Instance != null)
            {
                if (PlayerController.Instance.halfMana)
                {
                    SaveData.Instance.LoadShadeData();
                    if(SaveData.Instance.sceneWithShade == SceneManager.GetActiveScene().name || SaveData.Instance.sceneWithShade == "")
                    {
                        Instantiate(shade, SaveData.Instance.shadePos, SaveData.Instance.shadeRot);
                    }
                }
            }
    
            SaveScene();
            DontDestroyOnLoad(gameObject);
            bench = FindObjectOfType<Bench>();
    
            SaveData.Instance.LoadBossData();
            
        }
    
        public void ResetData()
        {
            SaveData.Instance.DeleteAllSaveData();
        }
    
        private void Update()
        {
            if(Input.GetKeyDown(KeyCode.Escape) && !gameIsPaused)
            {
                pauseMenu.FadeUIIn(fadeTime);
                Time.timeScale = 0;
                gameIsPaused = true;
            }
        }
    
        public void UnpauseGame()
        {
            Time.timeScale = 1;
            gameIsPaused = false;
        }
    
        public void SaveScene()
        {
            string currentSceneName = SceneManager.GetActiveScene().name;
            SaveData.Instance.sceneNames.Add(currentSceneName);
            SaveData.Instance.SaveSceneData(); // Save scene names whenever a new scene is added
        }
    
        public void RespawnPlayer()
        {
            SaveData.Instance.LoadBench();
            if (SaveData.Instance.benchSceneName != null) //load the bench's scene if it exists.
            {
                SceneManager.LoadScene(SaveData.Instance.benchSceneName);
            }
    
            if(SaveData.Instance.benchPos != null) //set the respawn point to the bench's position.
            {
                respawnPoint = SaveData.Instance.benchPos;
            }
            else
            {
                respawnPoint = platformingRespawnPoint;
            }
    
            PlayerController.Instance.transform.position = respawnPoint;
    
            StartCoroutine(UIManager.Instance.DeactivateDeathScreen());
            PlayerController.Instance.Respawned();
        }
    
        
        // Method to trigger pickup interaction event
        public void TriggerPickupInteract(string pickupID)
        {
            SaveData.Instance.AddCollectedPickup(pickupID); // Add pickup to SaveData
        }
    }
    
    #15019
    Elvin Sim
    Participant
    Helpful?
    Up
    0
    ::

    I try and try other way again and again but still cannot works

Viewing 15 posts - 16 through 30 (of 46 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: