Unity giving me errors even when my script is working

I’m using a depth sorting script I borrowed from the internet. I attach it to a GameObject that already has a Sprite Renderer attached to it. Here is the code:

using UnityEngine;
using System.Collections;

public class DepthSorter : MonoBehaviour
	private SpriteRenderer spriteRenderer;

	// Use this for initialization
	void Start ()
		spriteRenderer = GetComponent<SpriteRenderer>();

	void LateUpdate ()
		spriteRenderer.sortingOrder = (int)Camera.main.WorldToScreenPoint (spriteRenderer.bounds.min).y * -1;

The code works. It does what I want it to. However, Unity will not stop throwing the exact same error:

MissingComponentException: There is no 'SpriteRenderer' attached to the "DepthSorter" game object, but a script is trying to access it.
You probably need to add a SpriteRenderer to the game object "DepthSorter". Or your script needs to check if the component is attached before using it.
DepthSorter.LateUpdate () (at Assets/DepthSorter.cs:23)

Yes, there IS a SpriteRenderer, and not only is my script accessing it, but it is doing exactly what I want. What is going on here? What is the problem? Thanks so much for your help.

  1. Reimport all assets - i’ve had similar problem. “Reimport all” helps.

  2. It is good practice to check component existance before using

    if (spriteRenderer != null)
    spriteRenderer.sortingOrder = (int)Camera.main.WorldToScreenPoint (spriteRenderer.bounds.min).y * -1;

  3. Be careful with things as [HideInInspector] and HideFlags, it is possible, that you have more components on object that you are actually see.

Sorry it turned out that I of course was just being an idiot and had this script applied to another gameObject (besides the ones where it was working) and this other gameObject did NOT have a SpriteRenderer component and it was THAT instance that was giving me errors.