Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

Function called from preloader script doesn't change parent of gameobject (in the second scene)

Discussion in 'Scripting' started by Steegmens, Oct 23, 2020.

  1. Steegmens


    Aug 19, 2020
    Hi! I am trying to add the playerobject to my train object as a child, so it will move with the train when it moves instead of standing still. I created a manageChildren script, which simply makes a given object the child of the object which the script is on. This works perfectly but not when I want to call it from my gameController script on my preload scene.

    The function is being called since I can get a debug message from it, but it just won't change the parent of the object.
    This is my manageChildren script:
    Code (CSharp):
    1.     using System.Collections;
    2.     using System.Collections.Generic;
    3.     using UnityEngine;
    5.     public class manageChildren : MonoBehaviour
    6.     {
    7.         public GameObject childToBe;
    9.         public void ConnectChild()
    10.         {
    11.             childToBe.transform.parent = gameObject.transform;
    12.         }
    14.         public void DisconnectChild()
    15.         {
    16.             childToBe.transform.parent = null;
    17.         }
    18.     }
    This is how I call the function (from the preloader scene which has a DDOL script):

    Code (CSharp):
    1. public class GameController : MonoBehaviour
    2.     {
    3.         private manageChildren trainAndPlayer;
    5.         void Start()
    6.         {
    7.             StartCoroutine(LoadScene(sceneIterator));
    8.             trainAndPlayer = GameObject.Find("Trains").GetComponent<manageChildren>();
    9.             trainAndPlayer.ConnectChild();
    10.         }
    11.         private IEnumerator LoadScene(int sceneID){}
    12.     }
    I hope somebody can help me out. Thanks in advance!
  2. Kurt-Dekker


    Mar 16, 2013
    If line 8 relies on something being present from the scene load in line 7 (in
    ), it won't be: scenes are loaded at the end of frame and would never be available until the next frame, at the very earliest.

    You can trivially make
    void Start()
    into a coroutine by declaring it to return an
    , then put a while loop (with a
    yield return null;
    in it!!!) to wait until the scene loads and you find the "Trains" object, then proceed.

    Obviously you would need to interlock other things from going forward until that happens, such as things dependent on the
    quantity being non-null.
    MiguelAppStudio likes this.