Sunday, September 6, 2015

How to store variables in between scenes? Unity



How would that be possible, and would I be able to access them from anywhere?



Answer



There are multiple ways to go about this. One of them is by using PlayerPrefs, just save it in there (with Set commands) and get it later.


Make an object that doesn't get destroyed and set a static variable in that object. (This part is only known to me in C#, not specific to Unity.) Add the following script (or any other script that has a public static variable) to an object that will not be destroyed between levels (DontDestroyOnLoad call). This will, of course, get rid of the object if the player exits the game so it won't save it between sessions (only between level loads). (You can access the variable with scriptName.variableName, in the example's case StaticVariableHolder.myStaticInt, from any other script or object in the game):


public class StaticVariableHolder : MonoBehaviour {


public static int myStaticInt;
void Start ()
{
DontDestroyOnLoad(gameObject);
}
}

Make a public variable on an object that won't be destroyed then access that by finding that object later on:


public class StaticVariableHolder : MonoBehaviour {


public int myStaticInt;
void Start ()
{
DontDestroyOnLoad(gameObject);
}
}

Now in this case you need the other object's script to have these lines:


public class OtherScript : MonoBehaviour {

//this is the variable your
//gameobject with the script will be set to.
GameObject myCarrierObject;

void Start ()
{
myCarrierObject = GameObject.Find("persistentObject");
int myStaticInt = myCarrierObject.GetComponent().myStaticInt
}
}


Now, only the objects that has these lines will be able to access the object and its variables (not the last line where I set the int variable) so you have to make sure, you find the object with every other script that needs it. This makes the variable more protected but less accessible.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...