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

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:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
  
    public class manageChildren : MonoBehaviour
    {
        public GameObject childToBe;
  
        public void ConnectChild()
        {
            childToBe.transform.parent = gameObject.transform;
        }
  
        public void DisconnectChild()
        {
            childToBe.transform.parent = null;
        }
    }

This is how I call the function (from the preloader scene which has a DDOL script):

public class GameController : MonoBehaviour
    {
        private manageChildren trainAndPlayer;
  
        void Start()
        {
            StartCoroutine(LoadScene(sceneIterator));
            trainAndPlayer = GameObject.Find("Trains").GetComponent<manageChildren>();
            trainAndPlayer.ConnectChild();
        }
        private IEnumerator LoadScene(int sceneID){}
    }

I hope somebody can help me out. Thanks in advance!

If line 8 relies on something being present from the scene load in line 7 (in GameController), 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 IEnumerator, 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 trainAndPlayer quantity being non-null.

1 Like