0
votes

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
It looks like Resources.LoadAll is failing. You can prove this by doing Debug.Log(lettersAll .Length); under the Resources.LoadAll function. Let me know the sult of that log. Also, what directory did you put the Textures? Also, select the Texture and put a picture of the Import Settings for it.Programmer
The Textures folder is in Projects/Project Name/Assets/ and the Import Settings only worth mentioning is that I changed it to a Sprite & set the Sprite Mode to Multiple so I can cut letters everything else is at deffaultuser4464658

2 Answers

0
votes

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

0
votes

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