Forum begins after the advertisement:


[Part 15]Issues with LoadPickup

Home › Forums › Video Game Tutorial Series › Creating a Metroidvania in Unity › [Part 15]Issues with LoadPickup

Viewing 11 posts - 1 through 11 (of 11 total)
  • Author
    Posts
  • #20167
    Nirvik Rajbhandari
    Level 8
    Participant
    Helpful?
    Up
    0
    ::

    I was following Part 15 of the “Creating a Metroidvania in Unity series, and I was unable to find where LoadPickup was defined and also had an error with calling it, specifically, “‘GameManager.SaveData’ does not contain a definition for ‘Instance'” If it helps, I found that a view of the location of where the function is called is visible at around 19 minutes and 20 seconds into the video. Here is the GameManager script and if you happen to need any other scripts, the GitHub is here: https://github.com/KingPloof393/Metroidvania-Prototype/tree/main/Assets

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.SceneManagement;
    using Terresquall;
    using System.Threading.Tasks;
    
    [DisallowMultipleComponent]
    public class GameManager : PersistentObject
    {
        public string transitionedFromScene;
    
        public Vector2 platformingRespawnPoint;
        public Vector2 respawnPoint;
        public Vector2 defaultRespawnPoint;
    
        public Shade shadePrefab;
        Shade currentShade;
    
        [SerializeField] private UIScreen pauseMenu;
    
        public bool isPaused;
        float lastTimeScale = -1;
        static Coroutine stopGameCoroutine;
        public static bool isStopped {get { return stopGameCoroutine != null;}}
    
        public static SaveData globalData = new SaveData();
    
        public static GameManager Instance { get; private set; }
        private void Awake()
        {
            if(PlayerController.Instance != null)
            {
                if (globalData.shadeScene == SceneManager.GetActiveScene().name)
                {
                    SpawnShade(globalData.shadePosition, globalData.shadeRotation);
                }
            }
            if (Instance != null && Instance != this)
            {
                Destroy(gameObject);
                return;
            }
    
            Instance = this;
            DontDestroyOnLoad(gameObject);
            UpdateMap();
        }
    
        async void Start()
        {
            await Task.Delay(100);
            Bench.QuickLoad();
    
            SaveData.Instance.LoadPickupData();
            if (PlayerController.Instance != null)
            {
                if (PlayerController.Instance != null)
                {
                    if(globalData.shadeScene == SceneManager.GetActiveScene().name)
                    {
                        SpawnShade(globalData.shadePosition, globalData.shadeRotation);
                    }
                }
            }
        }
    
        public static Shade SpawnShade(Vector3 position, Quaternion rotation)
        {
            if(Instance.currentShade)
            {
                return null;
            }
            Instance.currentShade = Instantiate(Instance.shadePrefab, position, rotation);
            return Instance.currentShade;
        }
    
        protected override void Reset()
        {
            saveID = "GameManager";
            defaultRespawnPoint = FindObjectOfType<PlayerController>().transform.position;
            pauseMenu = FindObjectOfType<UIScreen>();
        }
    
        public void Update()
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                Pause(!isPaused);
            }
        }
    
        public void Pause(bool paused)
        {
            if(pauseMenu.IsAnimating())
            {
                return;
            }
    
            if(paused)
            {
                if(lastTimeScale < 0)
                {
                    lastTimeScale = Time.timeScale;
                }
                Time.timeScale = 0f;
                pauseMenu.Activate();
            }
            else
            {
                if(!isStopped)
                {
                    Time.timeScale = lastTimeScale > 0f ? lastTimeScale : 1f;
                    lastTimeScale = -1;
                }
                pauseMenu.Deactivate();
            }
            isPaused = paused;
        }
    
        public static void Stop(float duration = .5f, float restoreDelay = .1f, float slowMultiplier = 0f)
        {
            if (stopGameCoroutine != null) return;
            stopGameCoroutine = Instance.StartCoroutine(HandleStopGame(duration, restoreDelay, slowMultiplier));
        }
    
        static IEnumerator HandleStopGame(float duration, float restoreDelay, float slowMultiplier = 0f)
        {
            if(Instance.lastTimeScale < 0)
            {
                Instance.lastTimeScale = Time.timeScale;
            }
    
            Time.timeScale = Mathf.Max(0, Instance.lastTimeScale * slowMultiplier);
    
            WaitForEndOfFrame wait = new WaitForEndOfFrame();
            while (duration > 0)
            {
                if(Instance.isPaused)
                {
                    yield return wait;
                    continue;
                }
    
                Time.timeScale = Mathf.Max(0, Instance.lastTimeScale * slowMultiplier);
                duration -= Time.unscaledDeltaTime;
                yield return wait;
            }
    
            float timeScaleToRestore = Instance.lastTimeScale;
            Instance.lastTimeScale = -1;
            stopGameCoroutine = null;
    
    
            if (restoreDelay > 0)
            {
                float currentTimeScale = timeScaleToRestore * slowMultiplier;
                float restoreSpeed = (timeScaleToRestore - currentTimeScale) / restoreDelay;
                while (currentTimeScale < timeScaleToRestore)
                {
                    if(Instance.isPaused)
                    {
                        yield return wait;
                        continue;
                    }
    
                    if (isStopped) yield break;
    
                    currentTimeScale += restoreSpeed * Time.unscaledDeltaTime;
                    Time.timeScale = Mathf.Max(0, currentTimeScale);
    
                    yield return wait;
                }
            }
    
            if(!isStopped)
            {
                Time.timeScale = Mathf.Max(0, timeScaleToRestore);
            }
        }
    
        public void UpdateMap()
        {
            string currentSceneName = SceneManager.GetActiveScene().name;
            MapManager.data.visitedScenes.Add(currentSceneName);
        }
    
        public void RespawnPlayer(float manaPenalty = 0f)
        {
            if (!string.IsNullOrEmpty(globalData.lastScene) && globalData.lastScene != SceneManager.GetActiveScene().name)
            {
                SceneManager.LoadScene(globalData.lastScene);
                SavePoint sp = Bench.FindObjectBySaveID(globalData.benchSaveID) as SavePoint;
                if(sp)
                {
                    respawnPoint = sp.GetAnchorPosition();
                }
            }
            else
            {
                respawnPoint = defaultRespawnPoint;
            }
            PlayerController.Instance.transform.position = respawnPoint;
            UIManager.Instance.deathScreen.Deactivate();
            PlayerController.Instance.Respawn(manaPenalty);
        }
    
        public override PersistentObject.SaveData Save()
        {
            if (CanSave())
            {
                globalData.saveID = saveID;
                return globalData;
            }
    
            Debug.LogError("Failed to save");
            return null;
        }
    
        public override bool Load(PersistentObject.SaveData data)
        {
            if (data == null)
            {
                return false;
            }
            globalData = data as SaveData;
            if (globalData == null)
            {
                return false;
            }
            return true;
        }
    
        [System.Flags]
        public enum Flags : long { None = 0, BossDefeated = 1 }
        public static bool Is(Flags f) { return globalData.flags.HasFlag(f); }
        public static void Set(Flags f, bool on)
        {
            if(on) globalData.flags |= f;
            else {globalData.flags &= f; }
        }
    
        [System.Serializable]
        public new class SaveData : PersistentObject.SaveData
        {
            public string lastScene;
            public string benchSaveID;
            public string shadeScene;
            public float shadePositionX, shadePositionY, shadePositionZ;
            public float shadeRotationX, shadeRotationY, shadeRotationZ, shadeRotationW;
            public Flags flags;
    
            public Vector3 shadePosition
            {
                get { return new Vector3(shadePositionX, shadePositionY, shadePositionZ); }
                set
                {
                    shadePositionX = value.x;
                    shadePositionY = value.y;
                    shadePositionZ = value.z;
                }
            }
            public Quaternion shadeRotation
            {
                get { return new Quaternion(shadeRotationX, shadeRotationY, shadeRotationZ, shadeRotationW); }
                set
                {
                    shadeRotationX = value.x;
                    shadeRotationY = value.y;
                    shadeRotationZ = value.z;
                    shadeRotationW = value.w;
                }
            }
        }
    }
    #20168
    Terence
    Level 32
    Keymaster
    Helpful?
    Up
    0
    ::

    I’ve enabled AI replies on your post. Let’s see what Onki says first.

    #20169
    Nirvik Rajbhandari
    Level 8
    Participant
    Helpful?
    Up
    0
    ::

    Ok, thank you!

    #20171
    Onki Apustaja
    Level 3
    AI Reply Bot
    Helpful?
    Up
    0
    ::

    Hello Nirvik! First, please note that I was unable to retrieve data from the knowledge base for this reply, so we will be navigating through this structural bug using the code you’ve directly provided here.

    Let’s examine the architecture of your GameManager script step-by-step to see why the compiler is getting lost when you call SaveData.Instance.LoadPickupData();.

    Step 1: Uncovering the Naming Collision (The “Shadowing” Effect)

    Take a look at the very bottom of your GameManager script:

    [System.Serializable]
    public new class SaveData : PersistentObject.SaveData
    {
        public string lastScene;
        // ...

    Notice that GameManager defines its own internal, nested class named SaveData (inherited from PersistentObject.SaveData).

    Now, when you are inside GameManager‘s Start() method and write:

    SaveData.Instance.LoadPickupData();

    The C# compiler looks for the closest definition of SaveData within your current scope. Because you are inside GameManager, it immediately finds GameManager.SaveData rather than any external SaveData script or singleton you might have created earlier in the series. Since GameManager.SaveData is just a plain data container (stored in the globalData variable) and does not have a public static SaveData Instance property, the compiler halts and reports: > 'GameManager.SaveData' does not contain a definition for 'Instance'


    Step 2: Tracing the Two Possible Paths Forward

    In the evolution of the Metroidvania series, the save system undergoes a large structural overhaul where an older standalone SaveData singleton transitions into the Bench and PersistentObject architecture. Depending on how your other scripts are currently set up, we have two paths to check:

    Path A: You still have a separate SaveData.cs script in your project

    If you have an older, standalone script named SaveData.cs in your project that holds Instance and LoadPickupData(), the nested class inside GameManager is “shadowing” (hiding) it.

    To tell C# to look outside of GameManager and find the standalone script in the global namespace, you can use the global:: scope qualifier inside Start():

    global::SaveData.Instance.LoadPickupData();

    (Alternatively, if SaveData.cs is inside a specific namespace, you would prefix it with that namespace, such as YourNamespace.SaveData.Instance.LoadPickupData();).

    Path B: Pickups were migrated to PersistentObject and Bench

    If you no longer have a standalone SaveData.cs script with LoadPickupData(), let’s trace how the new save system works in your script. Notice the line right above your error in Start():

    await Task.Delay(100);
    Bench.QuickLoad();

    In the revamped save architecture, objects that need to remember their state across scenes (like Pickups, Heart Shards, or Orb Shards) inherit from PersistentObject instead of relying on a separate LoadPickupData() method. When Bench.QuickLoad() runs, it automatically finds all PersistentObject instances in the scene and calls their Load() methods.

    If your pickup scripts (or a dedicated manager like HeartShards / Pickup) have already been converted to inherit from PersistentObject, then Bench.QuickLoad() is already handling the loading for you! In that case, SaveData.Instance.LoadPickupData(); is a leftover line from the older save system before the refactor, and can safely be removed or commented out.


    Next Steps to Explore

    To be completely sure which path applies to your current project state:

    1. Check your Unity Project window to see if you have a standalone script named SaveData.cs.
    2. If you do, open it up and check if LoadPickupData() is defined inside it (if so, Path A will resolve your error!).
    3. If you don’t have that script—or if it has been replaced by Bench.cs and PersistentObject.cs—feel free to share the contents of your pickup script (or Bench.cs) here, and we can trace exactly how your pickups are being saved and loaded together!
    #20172
    Nirvik Rajbhandari
    Level 8
    Participant
    Helpful?
    Up
    0
    ::

    I do not have a script that is called SaveData as I believe we were supposed to delete it in the video. I also do not have a script called Bench anymore as it has been renamed to SavePoint. Bench instead refers to the Terresquall Bench Asset Pack. Addiitionally, here it the pickup script, though I do not know if it will be of much help.

    using System.Collections; using System.Collections.Generic; using UnityEngine; using Terresquall;

    public abstract class Pickup : PersistentObject { protected bool used;

    [Tooltip("How long after touching the pickup before the Use() function fires.")]
    public float useDelay = 0f;
    
    [Tooltip("How long after touching the pickup before the Used() function fires.")]
    public float usedDelay = 0f;
    
    [System.Serializable]
    public struct Animation
    {
        public float frequency;
        public Vector3 direction;
        public Vector3 torque;
    
        [Tooltip("Effect that plays when pickup is touched")]
        public ParticleSystem destroyEffectPrefab;
        [Tooltip("Effect that plays on the target affected by the pickup")]
        public ParticleSystem targetEffectPrefab;
    }
    
    public Animation animation = new Animation
    {
        frequency = 2f,
        direction = new Vector2(0, 0.3f)
    };
    Vector3 initialPosition;
    float initialOffset;
    
    protected virtual void Update()
    {
        transform.position = initialPosition + animation.direction * Mathf.Sin((Time.time + initialOffset) * animation.frequency);
        transform.Rotate(animation.torque * Time.deltaTime);
    }
    
    protected virtual void Start()
    {
        initialPosition = transform.position;
        initialOffset = Random.Range(0, animation.frequency);
    }
    
    protected virtual void OnTriggerEnter2D(Collider2D _other)
    {
        if (used)
        {
            return;
        }
    
        if (_other.TryGetComponent(out PlayerController _player))
        {
            StartCoroutine(HandleUse(_player));
        }
    }
    
    public virtual void Touch(PlayerController _player)
    {
        if(animation.destroyEffectPrefab)
        {
            ParticleSystem fx = Instantiate(animation.destroyEffectPrefab, transform.position, Quaternion.identity);
            Destroy(fx, fx.main.duration);
        }
    }
    
    public virtual void Use(PlayerController _player)
    {
        used = true;
        if (animation.targetEffectPrefab)
        {
            ParticleSystem fx = Instantiate(animation.targetEffectPrefab, _player.transform);
            Destroy(fx, fx.main.duration);
        }
    }
    
    public virtual void Used(PlayerController _player)
    {
        gameObject.SetActive(false);
    }
    
    protected virtual IEnumerator HandleUse(PlayerController _player)
    {
        Touch(_player);
    
        yield return Delay(useDelay);
        Use(_player);
    
        yield return Delay(usedDelay);
        Used(_player);
    }
    
    protected virtual IEnumerator Delay(float _duration)
    {
        WaitForSecondsRealtime wait = new WaitForSecondsRealtime(.05f);
        while (_duration > 0)
        {
            yield return wait;
            if (!GameManager.Instance.isPaused)
            {
                _duration -= wait.waitTime;
            }
        }
    }
    
    [System.Serializable]
    public new class SaveData : PersistentObject.SaveData
    {
        public bool used;
    }
    
    public override PersistentObject.SaveData Save()
    {
        if (CanSave() && used)
            return new SaveData { used = used };
        return null;
    }
    
    public override bool Load(PersistentObject.SaveData data)
    {
        SaveData save = (SaveData)data;
        if(save != null && save.used)
        {
            Destroy(gameObject);
            return true;
        }
        return false;
    }

    }

    #20173
    Onki Apustaja
    Level 3
    AI Reply Bot
    Helpful?
    Up
    0
    ::

    Thanks for sharing the Pickup script and clarifying your project’s current structure, Nirvik! That script is actually the exact missing piece of the puzzle we needed.

    Let’s trace what your Pickup script and the Terresquall Bench asset pack are doing together so we can see why that error is appearing and how to resolve it cleanly.

    Step 1: How Pickups Are Loaded Now

    Look at the class declaration and the bottom of your Pickup.cs script:

    public abstract class Pickup : PersistentObject
    {
        // ...
        public override PersistentObject.SaveData Save()
        {
            if (CanSave() && used)
                return new SaveData { used = used };
            return null;
        }
    
        public override bool Load(PersistentObject.SaveData data)
        {
            SaveData save = (SaveData)data;
            if(save != null && save.used)
            {
                Destroy(gameObject);
                return true;
            }
            return false;
        }
    }

    Because Pickup inherits from PersistentObject (from the Terresquall Bench asset pack) and overrides Save() and Load(), it is now completely self-sufficient.

    When your GameManager runs Bench.QuickLoad(); in Start(), the Terresquall Bench system automatically finds every PersistentObject in the scene—including all of your pickups—and calls their Load() method directly. If a pickup was previously collected (save.used), it destroys itself automatically.

    Step 2: Why the Error Happened

    Before you transitioned to the Terresquall Bench asset pack and deleted the old SaveData.cs script, pickups had to be loaded manually via SaveData.Instance.LoadPickupData();.

    When SaveData.cs was deleted during the tutorial refactor, that line in GameManager.Start() became an leftover artifact from the old save system. Because it was left behind, the compiler tried to make sense of SaveData by looking at your nested GameManager.SaveData class instead, resulting in the 'GameManager.SaveData' does not contain a definition for 'Instance' error.

    Step 3: The Fix

    Since Bench.QuickLoad() is now doing all the heavy lifting for your Pickup objects, you simply need to remove (or comment out) SaveData.Instance.LoadPickupData(); inside GameManager.cs:

        async void Start()
        {
            await Task.Delay(100);
            Bench.QuickLoad();
    
            // Remove or comment out this leftover line from the old save system:
            // SaveData.Instance.LoadPickupData();
    
            if (PlayerController.Instance != null)
            {
                if(globalData.shadeScene == SceneManager.GetActiveScene().name)
                {
                    SpawnShade(globalData.shadePosition, globalData.shadeRotation);
                }
            }
        }

    (Note: I also cleaned up the duplicate if (PlayerController.Instance != null) check that was nested inside itself in Start().)

    Once you remove that line, your project should compile cleanly, and your pickups will load their saved states automatically through Bench.QuickLoad(). Give that a try and let me know if everything runs smoothly!

    #20174
    Nirvik Rajbhandari
    Level 8
    Participant
    Helpful?
    Up
    0
    ::

    I dont think the game is being loaded at all as it says it is saving, but the player spawns at the start without any abilities or shards. Additionally, the save point script’s anchor mechanic doesnt work as the player just falls down. Github has been updated https://github.com/KingPloof393/Metroidvania-Prototype/tree/main/Assets

    #20175
    Onki Apustaja
    Level 3
    AI Reply Bot
    Helpful?
    Up
    0
    ::

    First, please note that I still could not retrieve data from the knowledge base for this reply, nor can I browse external GitHub links directly. However, we can still map out and solve these two issues together by looking at how PersistentObject, Bench, and SavePoint interact with your GameManager and PlayerController.

    When the game says it is saving, yet your player spawns at the default start with no abilities or shards—and falls right through the save point when anchoring—there are two distinct structural threads we need to trace. Let’s walk through them one by one.


    Thread 1: Why the Game Isn’t Loading Abilities, Shards, or Position

    In the Terresquall Bench system, Bench.QuickSave() and Bench.QuickLoad() rely on three specific links in a chain. If any single link is missing, the save file will either fail to record your player’s data or fail to apply it on startup:

    1. Matching saveIDs on PersistentObjects

    Every script that inherits from PersistentObject (such as GameManager, PlayerController, and Pickup) has a Save ID field in the Unity Inspector.

    • If saveID is empty, CanSave() returns false, and the object is completely ignored during saving and loading.
    • Verify in the Inspector on your Player and GameManager GameObjects that their Save ID field is populated (for example, "Player" and "GameManager").
    • Also look at the Save() method in your GameManager (and check PlayerController.Save() as well):
      public override PersistentObject.SaveData Save()
      {
          if (CanSave())
          {
              globalData.saveID = saveID;
              return globalData;
          }

      In Pickup.cs, notice that saveID wasn’t assigned to the returned SaveData:

      public override PersistentObject.SaveData Save()
      {
          if (CanSave() && used)
              return new SaveData { saveID = saveID, used = used }; // Ensure saveID is included!
          return null;
      }

      If saveID is not copied into the returned SaveData object (or passed into its constructor), Bench.QuickLoad() won’t know which object in the scene that saved data belongs to! Check PlayerController.Save() to make sure saveID = this.saveID is being set on the player’s SaveData before it is returned.

    2. Calling RespawnPlayer() After Loading in GameManager.Start()

    Look closely at GameManager.Start() in the script you shared earlier:

        async void Start()
        {
            await Task.Delay(100);
            Bench.QuickLoad();
    
            if (PlayerController.Instance != null)
            {
                if(globalData.shadeScene == SceneManager.GetActiveScene().name)
                {
                    SpawnShade(globalData.shadePosition, globalData.shadeRotation);
                }
            }
        }

    Notice what happens right after Bench.QuickLoad();: GameManager.Load() puts the loaded data into globalData (including globalData.lastScene and globalData.benchSaveID), but Start() never actually moves the player to the saved bench!

    Because RespawnPlayer() is never called in Start() (or inside GameManager.Load()), your player just stays wherever they were placed in the scene editor.


    Thread 2: Why the SavePoint Anchor Mechanic Lets the Player Fall

    When your player interacts with a SavePoint (bench), the anchor mechanic usually moves the player to the bench’s anchor position (which is often slightly above the ground, on the seat of the bench) and locks them in a sitting/resting state.

    If the player immediately falls down when anchoring, one of two things is happening in the physics/controller loop:

    1. Gravity and Velocity are still active: When the player enters the anchored/sitting state on the SavePoint, the Rigidbody2D gravity scale isn’t being zeroed out (or rb.bodyType isn’t being set to Kinematic/Static), or PlayerController.Update() / FixedUpdate() is still running its normal movement and gravity code and overwriting the anchor position.
    2. Collider / Trigger mismatch: If the bench seat relies on a physical collider to hold the player up, or if anchoring disables the player’s collider while leaving Rigidbody2D dynamic, gravity will pull the player straight down through the floor or bench.

    Let’s Inspect the Scripts Together

    Since I cannot view your GitHub repository directly, could you paste the code for these two scripts right here in your next reply?

    1. SavePoint.cs (so we can see how it calls Bench.QuickSave() and how GetAnchorPosition() / anchoring the player is implemented)
    2. PlayerController.cs (specifically the Save() and Load() methods at the bottom, and any bench/sitting state logic)

    Once you share those two scripts here, we can pinpoint the exact lines causing both the save data drop and the falling anchor bug!

    #20176
    Nirvik Rajbhandari
    Level 8
    Participant
    Helpful?
    Up
    0
    ::

    If it helps, if I go to another scene it just gives a nullreference error next time I load as it starts in scene 1 and doesnt load the correct scene. Additionally, its giving this error when it saves if it helps. IOException: Sharing violation on path C:\Users\nirvi\AppData\LocalLow\DefaultCompany\Metroidvania Prototype\saves\0.txt System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0) System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0) (wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare) System.IO.File.Open (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0) System.IO.File.Open (System.String path, System.IO.FileMode mode) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0) Terresquall.Bench.ReadSaveFile (System.Int32 slot) (at Assets/Bench Universal Save System/Scripts/Bench.cs:371) Terresquall.Bench.ReadAndFind (Terresquall.PersistentObject p, System.Int32 slot) (at Assets/Bench Universal Save System/Scripts/Bench.cs:114) Terresquall.PersistentObjectEditor.DrawSaveDataInspector (UnityEngine.GUIStyle style) (at Assets/Bench Universal Save System/Scripts/Editor/PersistentObjectEditor.cs:78) Terresquall.PersistentObjectEditor.OnInspectorGUI () (at Assets/Bench Universal Save System/Scripts/Editor/PersistentObjectEditor.cs:27) UnityEditor.UIElements.InspectorElement+<>c__DisplayClass59_0.<CreateIMGUIInspectorFromEditor>b__0 () (at <f3c908ec2db6459da6ee3ebe6da5021b>:0) UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

    #20177
    Nirvik Rajbhandari
    Level 8
    Participant
    Helpful?
    Up
    0
    ::

    No longer giving the error, but it doesnt load pickups being collected when transitioning between scenes. Sorry for filling up this chat with a lot of yap.

    #20178
    Onki Apustaja
    Level 3
    AI Reply Bot
    Helpful?
    Up
    0
    ::

    Please don’t apologize at all, Nirvik! Debugging a save and scene-transition system involves tracing many moving parts at once, and every detail you share helps map out what the engine is doing behind the scenes. It is great to hear that the IOException file-sharing conflict cleared up! (For future reference, that particular error usually happens when a PersistentObject is selected in the Unity Inspector while the game is actively writing to 0.txt, as the custom Inspector tries to read the file at the exact same moment).

    Let’s walk through the remaining hallways of this labyrinth: why pickups don’t stay collected when transitioning between scenes, and why starting the game in Scene 1 fails to load your last saved scene and triggers a NullReferenceException.


    Path 1: Why Pickups Don’t Load Their Collected State Between Scenes

    To see why pickups reappear or fail to load when you walk from one scene to another, let’s trace the lifecycle of your GameManager:

    1. In GameManager.Awake(), you call DontDestroyOnLoad(gameObject);. This means GameManager is created once when the game starts, and survives every scene transition without ever being recreated.
    2. In Unity, Start() only runs once in a GameObject’s entire lifetime. Therefore, Bench.QuickLoad() inside GameManager.Start() only runs when you first press Play.
    3. When you walk into a new scene (or return to a previous scene), new Pickup objects are spawned as part of that scene load. However, because GameManager.Start() does not run again, Bench.QuickLoad() is never called for those newly spawned pickups!

    At the same time, look closely at your Pickup.Save() method from earlier:

        public override PersistentObject.SaveData Save()
        {
            if (CanSave() && used)
                return new SaveData { used = used };
            return null;
        }

    Notice two critical things here:

    1. Assigning the saveID: Unlike GameManager.Save() (where you wrote globalData.saveID = saveID;), Pickup.Save() creates a new SaveData { used = used } without assigning saveID = this.saveID! Without its saveID attached to the data, Bench won’t know which pickup in the scene that saved record belongs to when Bench.QuickLoad() runs.
    2. Saving when collected or leaving a scene: If you collect a pickup and immediately walk into another scene without sitting at a SavePoint first, Pickup.Save() is only recorded to disk if Bench.QuickSave() (or Save() on that pickup) was triggered when you collected it.

    Let’s fix both ends of this connection:

    Step 1A: Include saveID (and trigger a save) in Pickup.cs

    In Pickup.cs, make sure saveID is stored in the SaveData object, and consider saving when the pickup is used:

        public override PersistentObject.SaveData Save()
        {
            if (CanSave() && used)
                return new SaveData { saveID = saveID, used = used };
            return null;
        }

    (Also double-check in the Unity Inspector that every Pickup in your scenes has a unique Save ID string filled in!)

    Step 1B: Trigger Bench.QuickLoad() on Scene Transitions in GameManager.cs

    To ensure that any PersistentObject (like a Pickup) in a newly loaded scene has its Load() method called, we can subscribe to Unity’s SceneManager.sceneLoaded event inside GameManager:

        private void Awake()
        {
            if(PlayerController.Instance != null)
            {
                if (globalData.shadeScene == SceneManager.GetActiveScene().name)
                {
                    SpawnShade(globalData.shadePosition, globalData.shadeRotation);
                }
            }
            if (Instance != null && Instance != this)
            {
                Destroy(gameObject);
                return;
            }
    
            Instance = this;
            DontDestroyOnLoad(gameObject);
            UpdateMap();
    
            // Listen for scene transitions
            SceneManager.sceneLoaded += OnSceneLoaded;
        }
    
        private void OnDestroy()
        {
            // Clean up the event listener if this object is destroyed
            SceneManager.sceneLoaded -= OnSceneLoaded;
        }
    
        private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
        {
            // Load state for any PersistentObjects (like Pickups) in the newly loaded scene
            Bench.QuickLoad();
            UpdateMap();
        }

    Path 2: Why the Game Starts in Scene 1 Instead of the Saved Scene (and Causes a NullReferenceException)

    Now let’s trace what happens when you save in Scene 2, stop the game, and press Play again in Scene 1:

    1. Look at GameManager.Start():

      async void Start()
      {
          await Task.Delay(100);
          Bench.QuickLoad();

      When Bench.QuickLoad() runs, it loads globalData.lastScene (which is "Scene 2"). However, GameManager.Start() never calls RespawnPlayer(), so the game never actually transitions to globalData.lastScene!

    2. Even if RespawnPlayer() is called, look closely at how RespawnPlayer() is currently written in your GameManager:

      public void RespawnPlayer(float manaPenalty = 0f)
      {
          if (!string.IsNullOrEmpty(globalData.lastScene) && globalData.lastScene != SceneManager.GetActiveScene().name)
          {
              SceneManager.LoadScene(globalData.lastScene);
              SavePoint sp = Bench.FindObjectBySaveID(globalData.benchSaveID) as SavePoint;
              if(sp)
              {
                  respawnPoint = sp.GetAnchorPosition();
              }
          }

      Here lies a classic Unity trap: SceneManager.LoadScene() does not finish loading the new scene on that exact line of code. Unity schedules the scene load to complete on the next frame.

      Because the next line (SavePoint sp = Bench.FindObjectBySaveID(...)) runs immediately on the current frame, Unity is still inside Scene 1! The SavePoint from Scene 2 doesn’t exist yet, so sp is null, or PlayerController.Instance / UIManager.Instance is in the middle of being destroyed/reloaded, causing a NullReferenceException.

    How to Fix Start() and RespawnPlayer()

    First, call RespawnPlayer() inside GameManager.Start() right after Bench.QuickLoad():

        async void Start()
        {
            await Task.Delay(100);
            Bench.QuickLoad();
    
            // Move the player to the saved scene and bench after loading data
            RespawnPlayer();
    
            if (PlayerController.Instance != null)
            {
                if(globalData.shadeScene == SceneManager.GetActiveScene().name)
                {
                    SpawnShade(globalData.shadePosition, globalData.shadeRotation);
                }
            }
        }

    Next, if RespawnPlayer() needs to load a different scene, we should wait a moment (or let the scene finish loading) before searching for the SavePoint in that new scene. Because you are already using async / Task.Delay in GameManager, you can make RespawnPlayer wait a frame after calling SceneManager.LoadScene:

        public async void RespawnPlayer(float manaPenalty = 0f)
        {
            if (!string.IsNullOrEmpty(globalData.lastScene) && globalData.lastScene != SceneManager.GetActiveScene().name)
            {
                SceneManager.LoadScene(globalData.lastScene);
                // Wait briefly for the new scene and its SavePoints to finish initializing
                await Task.Delay(100);
            }
    
            if (!string.IsNullOrEmpty(globalData.benchSaveID))
            {
                SavePoint sp = Bench.FindObjectBySaveID(globalData.benchSaveID) as SavePoint;
                if (sp)
                {
                    respawnPoint = sp.GetAnchorPosition();
                }
            }
            else
            {
                respawnPoint = defaultRespawnPoint;
            }
    
            if (PlayerController.Instance != null)
            {
                PlayerController.Instance.transform.position = respawnPoint;
                PlayerController.Instance.Respawn(manaPenalty);
            }
    
            if (UIManager.Instance != null && UIManager.Instance.deathScreen != null)
            {
                UIManager.Instance.deathScreen.Deactivate();
            }
        }

    Notice how we also moved the Bench.FindObjectBySaveID(globalData.benchSaveID) check outside of the if (globalData.lastScene != SceneManager.GetActiveScene().name) block. Previously, if you saved at a bench in Scene 1 and loaded the game in Scene 1, it went straight to the else block (respawnPoint = defaultRespawnPoint;) and ignored your bench in Scene 1 completely!


    Next Steps

    Try applying these updates to Pickup.cs and GameManager.cs. If any issues remain—such as the player falling through the bench anchor or specific player stats not loading—please paste the code for SavePoint.cs and PlayerController.cs directly into your next reply, and we will trace through them together!

Viewing 11 posts - 1 through 11 (of 11 total)
  • You must be logged in to reply to this topic.

Go to Login Page →


Advertisement below: