- Home /
Duplicate Question
How do I reference something from another scene?
I searched everywhere for anwers and haven't found answers. I have a MainMenu script and there is a reference that becomes a null reference if i switch to my playscene. That MainMenu script is attached to a MainMenu gameobject (which is in the MainMenu scene) and to a button in the playscene, so I can use the methods inside. The problem is, that because its in the playscene too, it cant reference a text because it doesn't exist in the playscene. I tried things like "DontDestroyOnLoad" but it doesn't work. I need to somehow reference it within playscene, but so that the text is still in the MainMenu scene. I dont know how to describe this. If you know an easier way to get rid of this NullReferenceExecption, then please tell me. I literally found nothing while digging in the internet.
The error: NullReferenceException: Object reference not set to an instance of an object MainMenu.Start () (at Assets/Scripts/MainMenu.cs:17)
private void Start()
{
_playerStats = FindObjectOfType<PlayerStats>().GetComponent<PlayerStats>();
_allMoneyText = FindObjectOfType<AllMoneyText1>().GetComponent<AllMoneyText1>();
_allMoneyText.ChangeMoneyText();
}
public void PlayGame()
{
SceneManager.LoadScene("Game");
}
public void BackToMainMenu()
{
_playerStats.AllMoney += _playerStats.money;
SceneManager.LoadScene("MainMenu");
SaveSystem.SavePlayer(_playerStats);
_allMoneyText.ChangeMoneyText();
Debug.Log(_playerStats.money);
Debug.Log(_playerStats.AllMoney);
}
public void QuitGame()
{
SaveSystem.SavePlayer(_playerStats);
Application.Quit();
}
}
You can't reference a gameObject present in a non loaded scene.
Either load that scene in additive, or save the data you want in your 1st scene and load that value in the 2nd scene.