Load scene with param variable Unity

2019-06-26 20:51发布

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?

2条回答
等我变得足够好
2楼-- · 2019-06-26 21:31

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:

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

using UnityEngine;
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).

查看更多
Evening l夕情丶
3楼-- · 2019-06-26 21:31

Maakep! Perfect and easy code!

But your method to load scene not working.

You can use another method:

UnityEngine.SceneManagement.SceneManager.LoadScene("Vuforia-4-Spheric");
查看更多
登录 后发表回答