skip to Main Content

I have started working on a new game and I want to make letters from a sprite sheet that change given the letter or number I give it. I created a numbers only sprite sheet in Photoshop just to test it and imported it into Unity as a Sprite. Then in a script I did this:

public string currLetter;

public string lettersName;

Sprite[] lettersAll;

void Awake () {

    lettersAll = Resources.LoadAll<Sprite> ("Textures/" + lettersName);
}

void Update () {

    switch (currLetter) {

    case "0":
        gameObject.GetComponent<SpriteRenderer> ().sprite = lettersAll[0];
        break;

    case "0":
        gameObject.GetComponent<SpriteRenderer> ().sprite = lettersAll[1];
        break;
    }
}

I am getting an error in the switch statement where if it’s for example number 1, it says that the array index is out of range and when I set the lettersAll to public it had 0 sprites. What am I doing wrong ? I have been trying to fix this all day but nothing works :/


Update:
Image of Sprite Sheet:

enter image description here

2

Answers


  1. Is your spritesheet under “Resources” folder?
    For your case the sprite file should be under “Resources/Textures/”

    Updated:
    I was able to duplicate the issue and solved it by making sure the following things are correct:

    1. Spritesheet under /Resources folder
    2. The spritesheet you are loading does have multiple sprites inside. If you see the screenshot posted here, spritesheet A,B,C,D
      will not be loaded because they have no sprites inside, even though
      the mode is set to multiple. Spritesheet E will be loaded correctly

    Spritesheet image

    Login or Signup to reply.
  2. Sprites of sprite sheet can’t be accessed like this, as the sprite sheet itself is a texture.

    Unity treats it like a texture internally, while giving you access to make it multiple and break it which is only accessed by the assigned reference.

    I would recommend don’t place your images in Resources, as it loads immediately at the start of the game, instead of the load at need.
    Try UI Sprite Manager which follows this

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search