问:
How do I pass information from my existing level to a new level that I'm about to load?
回答1:
The way I approach this is by taking any properties that need to be accessed from more than one scene and making them public variables in a script that is added to an empty GameObject and then I call Object.DontDestroyOnLoad on that object so it will persist through scene changes. Then it's a simple matter of using GameObject.Find to get thatGameObject
from a script in the new scene and GameObject.GetComponent to get the script. Then you can access the public variables of a persistent object from any script.
P.S. - GameObject.Find is fast but there's no need to call it every frame. To reference the persistent object script from another script, do something like this:
SomeObjectInTheNewSceneScript.js (pick a better name)
// if your persistent script is named `PersistenScript.js`
private persistentScript : PersistentScript;
function Start () {
// Start runs once early on and makes the connection to the other script
// so you don't have to do it every frame.
// if your persistent game object is named `Persistent Object`
var persistentGameObject : GameObject = GameObject.Find("Persistent Object");
persistentScript = persistentGameObject.GetComponent(PersistentScript);
}
then you can set/get properties of persistentScript
anywhere else in SomeObjectInTheNewSceneScript
回答2:
DontDestroyOnLoad, static, PlayerPrefs to hold variables between scenes.