So i have a scene called Lobby where i have a text input to type your nickname. My script gets the input from it when the button is pressed. Then, my script switches scenes, to go to Home scene, and i want my text element in this scene to be the name of the player. So i wanna know how should i do to “transfer” my variable from the script attached to a gameobject in “lobby” to a variable in a script attached to a gameobject in the scene “home”. I guess it has to do with non static classes but i really don’t know. Thanks.
Use a GameManager to store data between scenes.
If this means nothing to you, hurry to Youtube for tutorials and details about the concept of a GameManager.
If you are comfortable with the concept in general, here’s a few easy ways to start:
ULTRA-simple static solution to a GameManager:
OR for a more-complex “lives as a MonoBehaviour or ScriptableObject” solution…
Simple Singleton (UnitySingleton):
Some super-simple Singleton examples to take and modify:
Simple Unity3D Singleton (no predefined data):
Unity3D Singleton with a Prefab (or a ScriptableObject) used for predefined data:
These are pure-code solutions, DO NOT put anything into any scene, just access it via .Instance!
If it is a GameManager, when the game is over, make a function in that singleton that Destroys itself so the next time you access it you get a fresh one, something like:
public void DestroyThyself()
{
Destroy(gameObject);
Instance = null; // because destroy doesn't happen until end of frame
}
There are also lots of Youtube tutorials on the concepts involved in making a suitable GameManager, which obviously depends a lot on what your game might need.
OR just make a custom ScriptableObject that has the shared fields you want for the duration of many scenes, and drag references to that one ScriptableObject instance into everything that needs it. It scales up to a certain point.
If you really insist on a barebones C# singleton, here’s a highlander (there can only be one):
And finally there’s always just a simple “static locator” pattern you can use on MonoBehaviour-derived classes, just to give global access to them during their lifecycle.
WARNING: this does NOT control their uniqueness.
WARNING: this does NOT control their lifecycle.
public static MyClass Instance { get; private set; }
void OnEnable()
{
Instance = this;
}
void OnDisable()
{
Instance = null; // keep everybody honest when we're not around
}
Anyone can get at it via MyClass.Instance.
, and only while it exists.
Thanks so much for your answer, that helps me a lot, i was kinda stuck, i’m looking that up on youtube!