- Home /
GameObject Find isnt working in the same method with SceneManagment
Hello, I have the following problem: Im trying to swap to a scene(„samplescene“) using GameObject(this skript is attached to it) wich uses „DontDestroyOnLoad“ Then I want it to get a refference to a GameObject(„housespawner“) which I will use for the next steps (inside „samplescene“) The loading of the scene works fine, but the .Find method doesnt work in NewGame() which is confusing to me because the same command works if im manually doing it with Update()/GetKeyDown after I loaded the scene (Update() is just there,to show you the way it worked). So wheres the cause of not working when Im using it in the same method as SceneManager.LoadScene and what could be a solution. Or is there a even better way by not using .Find (I know its not very perfect). I was also searching for a way to refference housespawner immedialty, but the Gameobject with the skript is in the scene before. Thanks
public class GameManager : MonoBehaviour{
public void NewGame()
{
SceneManager.LoadScene("SampleScene");
houseSpawner = GameObject.Find("houseSpawner");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.K))
{
houseSpawner = GameObject.Find("houseSpawner");
}
}
}
Answer by Bonfire-Boy · Sep 07, 2021 at 11:01 AM
I guess the scene hasn't finished loading when you make that call. Try adding a callback like this...
private void Awake()
{
UnityEngine.SceneManagement.SceneManager.sceneLoaded += HandleSceneLoaded;
}
private void HandleSceneLoaded(UnityEngine.SceneManagement.Scene scene, UnityEngine.SceneManagement.LoadSceneMode mode)
{
houseSpawner = GameObject.Find("houseSpawner");
Debug.LogFormat("housspawner found: {0}", houespawner != null);
}
As for whether or not there's a better way than using Find... if this is something you just need to do once after the scene has loaded then I wouldn't worry about it too much tbh. But there are several alternatives. These include 1) if appropriate, which it looks like it might be, make the housespawner a singleton, 2) decouple the classes and control the Housespawner class using events (so that the GameManager doesn't need to have a reference to the housespawner at all) and 3) make the housespawner persist as well.
Your answer
Follow this Question
Related Questions
Access gameObject between multi-scene 0 Answers
Player wont be found on start 1 Answer
How to find a prefab in another scene? 1 Answer
How to find tags in scene? 1 Answer