Wierd NullReferenceException

Hi, I am geting this wierd NullReferenceException and don’t know why.
If I know right if the sprites var is empty the foreach shouldn’t do anything and the go object must be exist…
I got this error only when the game isn’t runing. How I got an error if the game isn’t runing?

    public override bool StartUp(Vector3Int position, ITilemap tilemap, GameObject go)
    {
        var sprites = go.transform.GetComponentsInChildren<SpriteRenderer>();
        foreach (var item in sprites)
        {
            item.sortingOrder = position.y * -1;
        }

        var mainSprite = go.transform.GetComponent<SpriteRenderer>();
        if(mainSprite!=null)
            mainSprite.sortingOrder = position.y * -1;

        return base.StartUp(position, tilemap, go);
    }

Error running StartUp for Tile.NullReferenceException: Object reference not set to an instance of an object
StaticDepth.StartUp (UnityEngine.Vector3Int position, UnityEngine.Tilemaps.ITilemap tilemap, UnityEngine.GameObject go) (at Assets/Scripts/TileMap/StaticDepth.cs:9)

NullReferenceException: Object reference not set to an instance of an object
StaticDepth.StartUp (UnityEngine.Vector3Int position, UnityEngine.Tilemaps.ITilemap tilemap, UnityEngine.GameObject go) (at Assets/Scripts/TileMap/StaticDepth.cs:9)

I changed the lines and the error always came from the first line of this function.

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.