Search Unity

Issue with Transfering Objects from Scene to Scene

Discussion in 'Scripting' started by roger0, Dec 3, 2018.

  1. roger0

    roger0

    Joined:
    Feb 3, 2012
    Posts:
    1,208
    I would like to transfer an object from one scene to another at runtime, and then be able to find references in the new scene. For my case I want to assign a parent to the transferring gameObject to another gameObject in the new scene. I call the dontDestroyOnLoad function to the transferring object. The gameObject appears in the new scene, however, its not able to find references, even after waiting for 5 seconds after the scene has been loaded.

    I've attached this code to the object that is being transfered.

    Code (CSharp):
    1.    public string levelName;
    2.     // Use this for initialization
    3.     void Start()
    4.     {
    5.         StartCoroutine("load");
    6.     }
    7.     public IEnumerator load () {
    8.         DontDestroyOnLoad(this.gameObject);
    9.         SceneManager.LoadSceneAsync(levelName, LoadSceneMode.Single);
    10.         GameObject parent = GameObject.Find("Plane");
    11.         yield return new WaitForSeconds(5);
    12.         transform.parent = parent.transform;
    13.     }

    I've also noticed that Unity separates the new scene and previous scene elements in the Hierarchy view. The last scene being called "DontDestroyOnLoad". In previous version of Unity, this didn't happen, and I don't necessarily want this. How can I make objects just merge into the new scene?



    I get this error after the Coroutine is finished

    NullReferenceException: Object reference not set to an instance of an object
    objectTransferScript+<load>c__Iterator0.MoveNext () (at Assets/scripts/Testing/objectTransferScript.cs:19)
    UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    I think you are trying to find the parent before the scene loads.
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    What you see in the editor has no effect on the build itself. The stuff isn't "separate", it's just split there to let you easily see that there is stuff set to dontdestroyonload and makes it much easier to sort out work developing.

    You should look into the SceneManager events to handle triggering code only after a scene finishes loading.