- Home /
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?
What's inside the pictures array? That's also relevant.
I don't understand why are you using an object[] for pictures, and not a Sprite[]. And if it's necessary, at least make it a safer cast, by checking that the object is of type sprite before casting.
exmaple:
if (pictures[counter] is Sprite)
GetComponent().sprite = pictures[counter] as Sprite;
I'm using object[] because I loaded the pictures out of a folder in Resources
Thank you, Notter! That worked perfectly. Not quite sure why, though since it wouldn't have actually changed anything since everything in pictures[] was a sprite. oh well ¯_(ツ)_/¯
Well, it might be that sometimes in the pictures array you actually didn't have a sprite. i can't see the rest of the code so i don't know for sure. but since it happens in Update(), it means every frame you change the sprite, so it might be for like 1 frame it doesn't work, and in the next it does, so you don't notice the frame the gives the error.
just a theory though.
Answer by DiegoSLTS · Jul 13, 2015 at 04:54 PM
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.