Can't reference game objects or components that were created during runtime

Hey! In my current project I am trying to reference the sprite renderer of an game object that I created during runtime but for some reason I am always getting NullReferenceException errors.

In the Backdrop.cs file (attached to a game object called “GameController”) I create the game object and add the sprite renderer component to it:

private void Start()
{
    GenerateBackdrop();
}

private void GenerateBackdrop()
{
    GameObject galaxyBackdrop = new GameObject("Galaxy Backdrop");
    galaxyBackdrop.transform.parent = transform;
    galaxyBackdrop.transform.position = new Vector3(0, 0, 1);

    SpriteRenderer renderer = galaxyBackdrop.AddComponent<SpriteRenderer>();
    renderer.sprite = galaxyImage[UnityEngine.Random.Range(0, 3)];
    renderer.drawMode = SpriteDrawMode.Sliced;
    renderer.size = new Vector2(unitsSize, unitsSize);

    renderer.sortingLayerName = "Backdrop";
    renderer.sortingOrder = 0;
}

And in the CameraController.cs (attached to my main camera) I try to reference the sprite renderer:

private void Start
{
    mapRenderer = GameObject.Find("Galaxy Backdrop").GetComponent<SpriteRenderer>();
}

Why isn’t this working and what can I do to solve this?
What is weird to me is that if I print GameObject.Find(“Galaxy Backdrop”).GetComponent() to the console and let it run in Update() it DOES find the correct object and component. Just not when it is running in Start()…

Your problem is that the CameraController is being created before the GameContoller.
Because of this the SpriteRenderer hasn’t yet been attached.

If you wish you can change the order scripts are executed.
Go to Edit->Project Settings->Script Execution Order.
Then add your script attached to GameController and move it above “Default Time”.

Hopefully, that should solve the problem.

Call theGenerateBackdrop(); method inside the Awake() function instead
https://docs.unity3d.com/Manual/ExecutionOrder.html
to make sure "Galaxy Backdrop" is created and ready to use by other scripts.
or
To communicate between the Backdrop and CameraController scripts when the “Galaxy Backdrop” game object is created, you could use a custom event-driven approach. Lets say the Backdrop script defines an event named BackdropCreatedEvent that is triggered when the game object is created. The CameraController subscribes to this event, and when triggered, it receives the SpriteRenderer reference and assigns it to the mapRenderer variable, allowing access to the component. This prevents NullReferenceException and ensures proper communication.