0

I am trying to change the image used for a sprite in unity, I am getting the error:NullReferenceException: Object reference not set to an instance of an object This has led me to believe that my loadall function is not working since it returns an array of null objects. Here is my code:

Sprite[] sprites = Resources.LoadAll<Sprite>("Sprite/Chests");

I then use the array with this line:

SpriteRender.sprite = sprites[SpriteIndex];
Joseph
  • 55
  • 1
  • 7
  • what is `SpriteRender`? can you add the line where you are creating this – ryeMoss Dec 03 '18 at 18:44
  • 2
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Fabjan Dec 03 '18 at 18:55
  • SpriteRender is the game component SpriteRenderer, as per line SpriteRender = gameObject.GetComponent(); – Joseph Dec 03 '18 at 22:14

2 Answers2

0

in the function Resources.LoadAll the path parameter is the path from Resources folder so Sprite/Chests must be under Resources folder. so your folder structure must be like this Resources -> Sprite -> Chests

Milad Qasemi
  • 3,011
  • 3
  • 13
  • 17
-1

Try doing:

Sprite[] sprites = Resources.LoadAll("Sprite/Chests", typeof(Sprite));

Otherwise you most likely have a path issue and you need to change your "Sprite/Chests" into the proper path.

Joe
  • 269
  • 3
  • 13
  • 1
    Your codeline and `Sprite[] sprites = Resources.LoadAll("Sprite/Chests");` as used by the OP are doing exactly the same thing. They just use different (old) overloads of the same method. So your answer doesn't add any additional information. – derHugo Dec 04 '18 at 17:45