How to access a GameObject in another scene?
I'm very new to Unity and I've encountered a problem. I've also searched online the internet but I can't find anything to help me. What I've tried already is loading the scene I want, then find the GameObject, like so:
public void LoadDioxygen()
{
SceneManager.LoadScene("Simulation", LoadSceneMode.Single);
GameObject.Find("Dioxygen").SetActive(false);
if (Input.GetKey(KeyCode.Space)) {
GameObject.Find("Dioxygen").SetActive(true);
Debug.Log("Active!");
}
}
However, this isn't working. What I've seen online is that I need to keep the Script Controller loaded but I really don't understand how that works. I saw DontDestroyOnLoad() being talked about but I really have no idea where to go at this point. What I'm trying to do is I have a menuscene and a simulationscene. What happens is when you click on a button you go to the simulationscene and it loads the GameObject I want it to load, and there are multiple buttons that loads different GameObjects. Also on the simulationscene there is a Menu button that when pressed, hides the current GameObject in the simulationscene and goes back to the menuscene.
Thank you all for your time! Please do tell me if you need more information.
Answer by jxng1 · Aug 16, 2019 at 11:11 AM
I had already tried the DontDestroyOnLoad but after testing it out for a bit, it appears that:
public void LoadDioxygen()
{
SceneManager.LoadScene("Simulation", LoadSceneMode.Single);/////at this line
GameObject.Find("Dioxygen").SetActive(false);
if (Input.GetKey(KeyCode.Space)) {
GameObject.Find("Dioxygen").SetActive(true);
}
}
at that line I get an error of NullReferenceException : Object reference not set to an instance of an object.
Perhaps this is what's causing everything to not work?
What I believe is happening is that it loads said the simulation scene but it's still trying to find the gameobject of Dioxygen in the current menuscene, which is why it is unable to find the gameobject as that gameobject doesn't exist in the menuscene? Would that be a correct assumption?
Answer by Vega4Life · Aug 15, 2019 at 07:14 PM
I would first try to add DontDestroy in your awake function of the above script. So add this:
private void Awake()
{
DontDestroyOnLoad(this);
}
Then the script sticks around and you should be able to find the game object. Although, it may not find it the first time... since you are loading the scene and immediately trying to find an object that may not be loaded yet.
Your answer
Follow this Question
Related Questions
Printing total time to open/loading a scene 0 Answers
Start function not called after reloading scene 0 Answers
Loading and Unloading scenes 2 Answers
Scene Manager and Keeping Objects when Loading/Unloading + Gameogject.SetActive not working:( 0 Answers
Unable to get name of current scene 0 Answers