Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Type mismatch error with Sprite

Discussion in '2D' started by Pykrete, Mar 5, 2021.

  1. Pykrete


    Jan 8, 2018
    When a player starts a new game there is a script that assigns a sprite to the character, using a class I've created called CharacterSprite (the class will do more later but right now it just stores a reference to a sprite).

    Code (CSharp):
    1. [System.Serializable]
    2. public class CharacterSprite
    3. {
    4.     public Sprite sprite;
    5. }
    Inside my character class it's just a reference to an instance of that object:

    Code (CSharp):
    1. public CharacterSprite sprite;
    I then have code elsewhere in the game that loads the character and assigns the sprite to a UI Image component, like this:

    Code (CSharp):
    1. public Image photo;
    3. public void UpdatePanel(Character character)
    4.     {
    5.         photo.sprite = character.sprite.sprite;
    6.         // Other code unrelated to the sprite
    7. }
    After I start a new game, the sprites load and display fine. I create a save file, then continue playing the game for some time, and the sprites continue to load and display without error.

    Then, after some period of time passes (the specific amount of time varies) when I play the game and go to the screen with the UpdatePanel function, I start getting the error

    "MissingReferenceException: The object of type 'Sprite' has been destroyed but you are still trying to access it.
    Your script should either check if it is null or you should not destroy the object."

    If I pause the game and view my Character object in the Inspector, the Sprite object says "Type mismatch."

    What would cause this error? The strange thing is that it all works just fine for some period of time, days or even weeks, and then suddenly I start getting the type mismatch error and it won't display the sprites any more.
  2. yicen233


    Sep 28, 2022
    Well, I met this problem ,could you tell me how to solve this problem? thank you
  3. Kurt-Dekker


    Mar 16, 2013
  4. Luke1986


    Feb 17, 2022
    Since this is a question about type mismatch and not NullReferenceException, I'll address that.
    All I know so far for myself is when I replace my Sprite with a new one via Sprite.Create, I get a type mismatch in all the Inspector references to it, which then leads to a NullReferenceException elsewhere. I feel like Sprite.Create should work.
    I offer this insight as another thing to hopefully cross off your list. As for me, I will continue my search.

    Best wishes.