Load scene with param variable Unity

DasBeasto picture DasBeasto · Feb 22, 2017 · Viewed 25.4k times · Source

In my game there is a map view that contains a 50x50 grid of tiles. When you click on the tile you get sent to that tiles view and attack things, etc. The only difference between these "tiles" as far as the code will be concerned is the tiles ID, aka. which number on the grid. That number will be passed to the server on init to handle the rest.

Obviously, with that being the only difference in tiles it would be a mistake to create a scene "1", scene "2"...scene "2500" and call SceneManager.LoadScene to switch to the specific tile view.

I could use DontDestroyOnLoad(); when the tile is clicked to preserve the tile ID on scene switch but 1) it only accepts gameobjects not just an int variable 2) I don't need/want to preserve that variable for anything more than the init in tile view. So while it could work it seems like overkill.

Is there a better practice for essentially just passing a parameter to a scene load?

Answer

Fredrik Schön picture Fredrik Schön · Feb 22, 2017

You can make a static class that holds the informaton for you. This class will not be attached to any GameObject and will not be destroyed when changing scene. It is static which means there can only be ONE of it; you can't write StaticClassName scn = new StaticClassName() to create new static classes. You access them straight through StaticClassName.SomeStaticMethod() for example and can be accessed from anywhere. See this example on how to store a value in a variable, change scene and then use it in that scene (please note the added using UnityEngine.SceneManagement;):

A normal Unity script attached to a gameobject in Scene "Test":

using UnityEngine;
using UnityEngine.SceneManagement;
public class TestingScript : MonoBehaviour {
    void Start()
    {
        StaticClass.CrossSceneInformation = "Hello Scene2!";
        SceneManager.LoadScene("Test2");
    }
}

A new static class (not inheriting from monobehaviour) that holds information:

public static class StaticClass {
    public static string CrossSceneInformation { get; set; }
}

A script attached to a game object in scene "Test2":

using UnityEngine;
public class TestingScript2: MonoBehaviour {

    void Start () {
        Debug.Log(StaticClass.CrossSceneInformation);
    }
}

You don't need to have the entire class static (if you for some reason need to create more instances of it). If you were to remove the static from the class (not the variable) you can still access the static variable through StaticClass.CrossSceneInformation but you can also do StaticClass sc = new StaticClass();. With this sc you can use the class's non-static members but not the static CrossSceneInformation since there can only be ONE of that (because it's static).