- Home /
How to use same code at multiple scenes ?
For example I'm gonna make a choice at "Choice.js"
public static var playerInt : int;
var playTypeString : String;
function Start()
{
playerInt = 0;
}
function Update () {
if(playerInt == 0) {
playTypeString = "sphere";
} else if(playerInt == 1) {
playTypeString = "stick";
} else if(playerInt == 2) {
playTypeString = "plus";
}
var text = gameObject.GetComponent(TextMesh);
text.text = playTypeString.ToString();
}
At there I've set public static variable. I want to get it's value at Game Scene and i use this;
function Start () {
if(Choice.playerInt == "0" ){
Debug.Log("player1");
}
if(Choice.playerInt == "1" ){
Debug.Log("player2");
}
}
But didn't work.
Answer by Landern · Sep 05, 2014 at 04:15 PM
Use DontDestroyOnLoad to mark the object not to be destroyed between scene loads, you're using a static var in that Choice script, should be good to go. Just add the DontDestroyOnLoad to the Awake function and reference the current object.
Note: Also be aware of the order your scripts execute.
But It's not the same scene. I'll go to Game from $$anonymous$$ain$$anonymous$$enu
But It's not the same scene. I'll go to Game from $$anonymous$$ain$$anonymous$$enu
Use DontDestroyOnLoad to mark the object not to be destroyed between scene loads, that is the point, it will retain and not destroy the object even though you're loading a different scene.
From the documentation if you cared to read it:
$$anonymous$$akes the object target not be destroyed automatically when loading a
new scene.
When loading a new level all objects in the scene are destroyed, then the objects in the new level are loaded. In order to preserve an object during level loading call DontDestroyOnLoad on it. If the object is a component or game object then its entire transform hierarchy will not be destroyed either.