Load scene with param variable Unity

后端 未结 2 1191
不知归路
不知归路 2021-02-20 07:00

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 betwee

2条回答
  •  悲&欢浪女
    2021-02-20 07:30

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

提交回复
热议问题