1
\$\begingroup\$

"Base" is in another scene but I thought Find will find it even if it's in another scene.

public class DronesManager : MonoBehaviour
{
    public GameObject target;
    public float movementSpeed;
    public float launchTime;

    public Transform dronesUnchild;

    private List<GameObject> drones = new List<GameObject>();
    private static System.Random rnd = new System.Random();

    private void Awake()
    {
        target = GameObject.Find("Base");
    }

but target is null when running the game.

this is a screenshot of the hierarhcy the script is attached to the Missile Launcher in the SampleScene and the "Base" is in the Example_01 scene.

hierarchy

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Do you get any different behaviour if you use Start instead of Awake? Start runs later, which might give enough time for the Example_01 scene to finish loading. \$\endgroup\$
    – DMGregory
    Nov 8 '21 at 23:00
  • \$\begingroup\$ @DMGregory indeed it's working in the Start. \$\endgroup\$ Nov 8 '21 at 23:19
1
\$\begingroup\$

Awake() gets called immediately as soon as the object has spawned/loaded. It's almost like a constructor, in that it will finish before a call to Instantiate() returns the newly spawned object.

That means that anything else that's being spawned in the same/subsequent pass is not necessarily in existence yet.

In this case, it's likely that your first scene loads and calls Awake() on all its objects before the second scene has finished loading, so the object simply doesn't exist yet to be found.

By moving your search to Start(), you delay it until just before the first Update() tick, giving time for the rest of the scene(s) to finish loading so their objects are ready for you to find.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .