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()…