- Home /
Loading Sprite from Sprite Sheet
I have a sprite sheet that contains the various parts of a human. The player can equip/unequip clothes, so the pieces from the basic sprite sheet will be swapped with pieces from another sheet. I need a way to load a single sprite from a sprite atlas.
According to similar questions, using Resources.LoadAll("File Name") is the way to go if the sprite atlas is in the Resources folder. I've tried this, and the Sprite Atlas always has an array size of 0.
Here is my code:
public Texture newSkin; //This is the sprite atlas I want the object to look like.
// Use this for initialization
void Start () {
//change out each child
// Head = sprite0
//-----
Sprite[] newSprites = Resources.LoadAll<Sprite>(newSkin.name);
Debug.Log ("Loaded " + newSkin.name + " with length: " + newSprites.Length);
transform.FindChild ("Head").GetComponent<SpriteRenderer> ().sprite = newSprites[0];
}
The Debug prints out: Loaded Template_Human1 with length: 0
The last line returns an IndexOutOfRange exception.
Answer by Masterio · May 22, 2017 at 07:45 AM
You should use some handlers for slots like: head, body, feets etc. it will boost performence.
I found something like that:
public Sprite GetSprite(string path, string name) { Object[] sprites = AssetDatabase.LoadAllAssetRepresentationsAtPath(path); if(sprites == null) return null; for(int i = 0; i < sprites.Length; i++) { if(sprites[i].name == name) return (Sprite) sprites[i]; } return null; }
It is not optimized probably but it works for me.
Inputs example: ("Assets/Textures/SkinAtlas_0", "Head")
I don't understand what you mean by "use some handlers". How do I change the name of the individual sprites in the atlas? Right now they all have the assigned names (Template_Human0, Template_Human1, etc).
I was able to get the sprites to swap out using AssetDatabase.LoadAllAssetRepresentationsAtPath(AssetDatabase.GetAssetPath(newSkin))
It is just suggestion about handlers:
replace this:
transform.FindChild ("Head").GetComponent<SpriteRenderer> ().sprite
for handler like this:
headRenderer = transform.FindChild ("Head").GetComponent<SpriteRenderer> ().sprite;
and add this property to the class:
SpriteRenderer headRenderer;
This is good when you want to replace sprites in game, otherwise you must always search head transform and sprite component and it takes some performence lose.
About names i dont know if there is possibility to change meybe in newer versions of unity, try click on sprite atlas file and press button Sprite Editor in inspector. If not works you must create new atlas with good names.
Your answer
Follow this Question
Related Questions
[ANDROID] Downloading large (4000x4000) textures causes a lot of memory consumption. 3 Answers
random sprite javascript 0 Answers
Load specific sprite from sprite sheet 1 Answer
InvalidOperationException: Operation is not valid due to the current state of the object. 1 Answer
Can't Optimize Huge Sprite Sheet 1 Answer