- Home /
Change language to all scenes
I want to change and save the language of the game from "Options" scene to all scenes. I can change and save the language only in "Options" scene from a dropdown list, but when I try to set the text from another scene i get this error: "Object reference not set to an instance of object". Script for "Options":
void Start()
{
if (PlayerPrefs.HasKey ("dropdown")) {
dropdown.value = PlayerPrefs.GetInt ("dropdown");
}
}
void Update () {
switch(dropdown.value)
{
case 0:
snd.text = "Volum sunet";
msc.text = "Volum muzica";
lng.text = "Limba";
menu.play.text="Joaca";
break;
case 1:
snd.text = "Sound volume";
msc.text = "Music volume";
lng.text = "Language";
menu.play.text="Play";
break;
}
PlayerPrefs.SetInt ("dropdown", dropdown.value);
}
Script for "Menu" scene
void Start()
{
if (PlayerPrefs.HasKey ("dropdown")) {
lang.dropdown.value=PlayerPrefs.SetInt("dropdown");
}
}
I don't really know to access dropdown value from another scene.
Answer by yoHasse · Jun 29, 2017 at 09:09 AM
You get this error because when loading the next scene the Option object in the last scene is destroyed. Therefore when you try to access it you get the error that the object doesn't exist. What you can do is to use "DontDestroyOnLoad(Object target);". This should keep the object from getting destroyed and then you should be able to reference it from the other scenes"Object reference not set to an instance of object". Script for "Options"
Reference:
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
Answer by Alex2k17 · Jun 29, 2017 at 10:46 AM
If I use DontDestroyOnLoad(Object target); on Script 1, automatically can I use reference to Script 2? Please note that I want to modify text, not objects.
Well no, "lang" needs to be referenced somewhere first in the Start method. Below are two different examples where "Option" is the name of your script.
lang = GetComponent<Option>(); //if the script is attached to the same gameobject
lang = FindObjectOfType<Option>().GetComponent<Option>();
//FindObjectOfType<Option>() finds the first gameobject with option component attached
//Gets the Option script attached to that object.
Referencing to other scripts is a really handy skill to have, I suggest that you look at some tutorials on Unitys website to learn some more.