C# Getting "Cannot cast from source type to destination type" even though it's working.

Relevant part of the script:

public object[] pictures;
public int counter = 1;

void  Update (){
GetComponent<SpriteRenderer>().sprite = (Sprite)pictures[counter];
}

This code works as it should, it changes the sprite of my GameObject to the desired object in the pictures array, the script works fine. But my only problem is that every frame the compiler gives me the “Cannot cast from source type to destination type” error, even though it works as it should. I would ignore this, but I’m pretty sure that when I try to build the game it wouldn’t let me until I fix this error.

What is wrong, and how do I fix it?

You said in the other comments that you’re using an object array because you’re loading the Sprites from Resources. Resources.Load and Resource.LoadAll both have a generic version where you can specify the type at compile time, and get references of that type only.

Sprite[] pictures = Resources.LoadAll<Sprite>(path);

You should use that instead of casts at runtime, it’s a lot safer.