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
- This topic has 10 replies, 3 voices, and was last updated 1 week ago by
Onki Apustaja.
-
AuthorPosts
-
November 25, 2026 at 8:06 am #20167::
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; } } } }November 25, 2026 at 9:30 am #20168November 25, 2026 at 9:41 am #20169November 25, 2026 at 10:30 am #20171::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
GameManagerscript step-by-step to see why the compiler is getting lost when you callSaveData.Instance.LoadPickupData();.Step 1: Uncovering the Naming Collision (The “Shadowing” Effect)
Take a look at the very bottom of your
GameManagerscript:[System.Serializable] public new class SaveData : PersistentObject.SaveData { public string lastScene; // ...Notice that
GameManagerdefines its own internal, nested class namedSaveData(inherited fromPersistentObject.SaveData).Now, when you are inside
GameManager‘sStart()method and write:SaveData.Instance.LoadPickupData();The C# compiler looks for the closest definition of
SaveDatawithin your current scope. Because you are insideGameManager, it immediately findsGameManager.SaveDatarather than any externalSaveDatascript or singleton you might have created earlier in the series. SinceGameManager.SaveDatais just a plain data container (stored in theglobalDatavariable) and does not have apublic static SaveData Instanceproperty, 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
SaveDatasingleton transitions into theBenchandPersistentObjectarchitecture. Depending on how your other scripts are currently set up, we have two paths to check:Path A: You still have a separate
SaveData.csscript in your projectIf you have an older, standalone script named
SaveData.csin your project that holdsInstanceandLoadPickupData(), the nested class insideGameManageris “shadowing” (hiding) it.To tell C# to look outside of
GameManagerand find the standalone script in the global namespace, you can use theglobal::scope qualifier insideStart():global::SaveData.Instance.LoadPickupData();(Alternatively, if
SaveData.csis inside a specific namespace, you would prefix it with that namespace, such asYourNamespace.SaveData.Instance.LoadPickupData();).Path B: Pickups were migrated to
PersistentObjectandBenchIf you no longer have a standalone
SaveData.csscript withLoadPickupData(), let’s trace how the new save system works in your script. Notice the line right above your error inStart():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
PersistentObjectinstead of relying on a separateLoadPickupData()method. WhenBench.QuickLoad()runs, it automatically finds allPersistentObjectinstances in the scene and calls theirLoad()methods.If your pickup scripts (or a dedicated manager like
HeartShards/Pickup) have already been converted to inherit fromPersistentObject, thenBench.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:
- Check your Unity Project window to see if you have a standalone script named
SaveData.cs. - If you do, open it up and check if
LoadPickupData()is defined inside it (if so, Path A will resolve your error!). - If you don’t have that script—or if it has been replaced by
Bench.csandPersistentObject.cs—feel free to share the contents of your pickup script (orBench.cs) here, and we can trace exactly how your pickups are being saved and loaded together!
November 25, 2026 at 11:24 am #20172::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; }}
November 25, 2026 at 12:30 pm #20173::Thanks for sharing the
Pickupscript 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
Pickupscript and the TerresquallBenchasset 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.csscript: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
Pickupinherits fromPersistentObject(from the TerresquallBenchasset pack) and overridesSave()andLoad(), it is now completely self-sufficient.When your
GameManagerrunsBench.QuickLoad();inStart(), the TerresquallBenchsystem automatically finds everyPersistentObjectin the scene—including all of your pickups—and calls theirLoad()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
Benchasset pack and deleted the oldSaveData.csscript, pickups had to be loaded manually viaSaveData.Instance.LoadPickupData();.When
SaveData.cswas deleted during the tutorial refactor, that line inGameManager.Start()became an leftover artifact from the old save system. Because it was left behind, the compiler tried to make sense ofSaveDataby looking at your nestedGameManager.SaveDataclass 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 yourPickupobjects, you simply need to remove (or comment out)SaveData.Instance.LoadPickupData();insideGameManager.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 inStart().)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!November 25, 2026 at 9:58 pm #20174::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
November 25, 2026 at 11:30 pm #20175::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, andSavePointinteract with yourGameManagerandPlayerController.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
Benchsystem,Bench.QuickSave()andBench.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 onPersistentObjectsEvery script that inherits from
PersistentObject(such asGameManager,PlayerController, andPickup) has aSave IDfield in the Unity Inspector.- If
saveIDis empty,CanSave()returnsfalse, and the object is completely ignored during saving and loading. - Verify in the Inspector on your Player and GameManager GameObjects that their
Save IDfield is populated (for example,"Player"and"GameManager"). - Also look at the
Save()method in yourGameManager(and checkPlayerController.Save()as well):public override PersistentObject.SaveData Save() { if (CanSave()) { globalData.saveID = saveID; return globalData; }In
Pickup.cs, notice thatsaveIDwasn’t assigned to the returnedSaveData:public override PersistentObject.SaveData Save() { if (CanSave() && used) return new SaveData { saveID = saveID, used = used }; // Ensure saveID is included! return null; }If
saveIDis not copied into the returnedSaveDataobject (or passed into its constructor),Bench.QuickLoad()won’t know which object in the scene that saved data belongs to! CheckPlayerController.Save()to make suresaveID = this.saveIDis being set on the player’sSaveDatabefore it is returned.
2. Calling
RespawnPlayer()After Loading inGameManager.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 intoglobalData(includingglobalData.lastSceneandglobalData.benchSaveID), butStart()never actually moves the player to the saved bench!Because
RespawnPlayer()is never called inStart()(or insideGameManager.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:
- Gravity and Velocity are still active: When the player enters the anchored/sitting state on the
SavePoint, theRigidbody2Dgravity scale isn’t being zeroed out (orrb.bodyTypeisn’t being set toKinematic/Static), orPlayerController.Update()/FixedUpdate()is still running its normal movement and gravity code and overwriting the anchor position. - 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
Rigidbody2Ddynamic, 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?
SavePoint.cs(so we can see how it callsBench.QuickSave()and howGetAnchorPosition()/ anchoring the player is implemented)PlayerController.cs(specifically theSave()andLoad()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!
November 26, 2026 at 12:03 am #20176::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&)
November 26, 2026 at 1:09 am #20177::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.
November 26, 2026 at 8:45 am #20178::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
IOExceptionfile-sharing conflict cleared up! (For future reference, that particular error usually happens when aPersistentObjectis selected in the Unity Inspector while the game is actively writing to0.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:- In
GameManager.Awake(), you callDontDestroyOnLoad(gameObject);. This meansGameManageris created once when the game starts, and survives every scene transition without ever being recreated. - In Unity,
Start()only runs once in a GameObject’s entire lifetime. Therefore,Bench.QuickLoad()insideGameManager.Start()only runs when you first press Play. - When you walk into a new scene (or return to a previous scene), new
Pickupobjects are spawned as part of that scene load. However, becauseGameManager.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:
- Assigning the
saveID: UnlikeGameManager.Save()(where you wroteglobalData.saveID = saveID;),Pickup.Save()creates anew SaveData { used = used }without assigningsaveID = this.saveID! Without itssaveIDattached to the data,Benchwon’t know which pickup in the scene that saved record belongs to whenBench.QuickLoad()runs. - Saving when collected or leaving a scene: If you collect a pickup and immediately walk into another scene without sitting at a
SavePointfirst,Pickup.Save()is only recorded to disk ifBench.QuickSave()(orSave()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) inPickup.csIn
Pickup.cs, make suresaveIDis stored in theSaveDataobject, 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 IDstring filled in!)Step 1B: Trigger
Bench.QuickLoad()on Scene Transitions inGameManager.csTo ensure that any
PersistentObject(like aPickup) in a newly loaded scene has itsLoad()method called, we can subscribe to Unity’sSceneManager.sceneLoadedevent insideGameManager: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:
-
Look at
GameManager.Start():async void Start() { await Task.Delay(100); Bench.QuickLoad();When
Bench.QuickLoad()runs, it loadsglobalData.lastScene(which is"Scene 2"). However,GameManager.Start()never callsRespawnPlayer(), so the game never actually transitions toglobalData.lastScene! -
Even if
RespawnPlayer()is called, look closely at howRespawnPlayer()is currently written in yourGameManager: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! TheSavePointfrom Scene 2 doesn’t exist yet, sospisnull, orPlayerController.Instance/UIManager.Instanceis in the middle of being destroyed/reloaded, causing aNullReferenceException.
How to Fix
Start()andRespawnPlayer()First, call
RespawnPlayer()insideGameManager.Start()right afterBench.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 theSavePointin that new scene. Because you are already usingasync/Task.DelayinGameManager, you can makeRespawnPlayerwait a frame after callingSceneManager.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 theif (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 theelseblock (respawnPoint = defaultRespawnPoint;) and ignored your bench in Scene 1 completely!
Next Steps
Try applying these updates to
Pickup.csandGameManager.cs. If any issues remain—such as the player falling through the bench anchor or specific player stats not loading—please paste the code forSavePoint.csandPlayerController.csdirectly into your next reply, and we will trace through them together! - Check your Unity Project window to see if you have a standalone script named
-
AuthorPosts
- You must be logged in to reply to this topic.
Advertisement below: