I'm working on a Unity project where I have a Singleton class, XPmanager
, which is responsible for managing XP data across multiple scenes. I'm using the DontDestroyOnLoad
method to make sure the XPmanager
instance is preserved when switching between scenes.
However, I've noticed that when I switch to another scene and then return back to the main scene, the Awake()
method of my XPmanager
is called twice, and the Instance IDs are different, indicating that a new instance is being created. This results in the loss of the XP data.
public class XPmanager : MonoBehaviour
{
public static XPmanager singleton;
// Other fields ...
private void Awake()
{
if (singleton == null)
{
singleton = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
// ...
}
// Other methods ...
}
I've checked that there's only one instance of the XPmanager
in my project. Despite using DontDestroyOnLoad
, the Awake()
method is called again with a different Instance ID when I switch back to the main scene.
Why is this happening, and how can I ensure that only a single instance of the XPmanager
is preserved across scene changes?
return
afterDestroy(gameObject)
. Is there code in that// ...
section that's being run by the instance that's in the process of self-destructing, because it didn't early-out because of that? If not, can you show a more complete example that clarifies exactly what symptoms show up, and what lines of code relate to those symptoms? \$\endgroup\$