NullReferenceException

I keep getting NullReferenceException when I create a spirte. It only happens when I close the application, but strangely not the first time I run the application, only after that. I must not be disposing of the texture properly. Can anyone help Here is some of my code:

        private void OnDeviceLost(object sender, EventArgs e)
        {
            if (Tile.sprite != null)
            {
               Tile.sprite.Dispose();
                Tile.sprite = null;
            }
        }

I also tried similiar code in the OnDestroyDevice method and still get the exception. Thank you for any suggestions.



Answer this question

NullReferenceException

  • Johan Levin

    I tried that and it did not work. I think it has something to do with static members, but I'm new at this so maybe not.
  • Joeouts

    You should also consider adding another condition to the if, making sure that Tile itself is not null. Therefore, instead of

    if (Tile.sprite != null)

    you should have

    if (Tile != null && Tile.sprite != null)


  • Roger Willcocks

    That's a good idea. I already removed Tile.sprite and created a spirte in the current class and still get the exception. I'm going nuts!
  • Scott Coffey

    hy. it might have an answer for you ...or not. maybe you should give up this line

    Tile.sprite = null ; // .sprite is already disposed.


  • NullReferenceException