Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Have a look at our Games Focus blog post series which will show what Unity is doing for all game developers – now, next year, and in the future.
    Dismiss Notice

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.