0

I'm using a GameObject with DontDestroyOnLoad() to store the player data and transition between scenes. Is there a way to have it call a Start() or equivalent method when the scene is changed(to populate the player data in the new scene) or will I need to place a utility object in each scene that calls the appropriate setup method in its own Start()

  • 1
    You can either do that, or try to detect when the scene is [finished loading](https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html?_ga=2.184504929.611814685.1618588150-152301318.1542389082). I am assuming when you say its own Start() method, you mean on Start() to search the scene for the other object of its same type, then call an Init() or something in the DontDestroyOnLoad existing object, to force it to set the data in the new scene and then destroy itself? – TEEBQNE Apr 20 '21 at 04:24

1 Answers1

4

You can either use e.g. SceneManager.sceneLoaded and attach a callback like e.g.

void Awake()
{
    DontDestroyOnLoad (gameObject);

    SceneManager.sceneLoaded += OnSceneLoaded;
}

// called second
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
    // Find your player and populate the data like e.g.
    var player = FindObjectOfType<Player>();

    player.SetData(....);       
}

private void OnDestroy ()
{
    SceneManager.sceneLoaded -= OnSceneLoaded;
}

Of course you could also go the other way round and simply let your player fetch the data as you mentioned yourself like

public class Player : MonoBehaviour
{
    private void Start ()
    {
        var manager = FindObjectOfType<PlayerManager>();

        var data = manager.GetData();

        ...
    }
}

In this case though the question is why even bother with DontDestroyOnLoad and does it have to be a MonoBehaviour at all?

You could as well simply make your data container static like

public static class PlayerData
{
    public static int someValue = 5;
}

and let your player(s) access them like

if(PlayersData.someValue <= 0)
{
    PlayerData.someValue = 10;
}

For more options actually see How to pass data between scenes in Unity

derHugo
  • 83,094
  • 9
  • 75
  • 115