- Home /
Directly refrencing a 9-spliced Sprite
I scoured the googles looking for some help, but failed to find a good way to solve this issue, but i happened to make something work. However id like to know if there is a better way to handle getting a specific spliced image.. for example, I have a file that has 3 different images Tab_Window, Tab_Active, Tab_Inactive all on the same sprite sheet. Each sprite has been 9 spliced.
I know how to do this within Unity Editor, but im trying to make a mod for another unity game outside of unity. like i said though .. i did manage to figure out a way to do it, but is there a better way than this
Image _backgroundImage = _canvasPanel.gameObject.AddComponent<Image>();
_backgroundImage.type = Image.Type.Sliced;
_backgroundImage.sprite = GetSpecificSprite("Tab_Inactive", "Images/Tabs");
public static Sprite GetSpecificSprite(string spriteName, string resourceLocation )
{
Sprite[] spritesheet = Resources.LoadAll<Sprite>($"{resourceLocation}");
if(spritesheet != null)
{
foreach (Sprite sprite in spritesheet)
{
if (sprite.name == $"{spriteName}")
{
return sprite;
}
}
}
Debug.Log($"Sprite {spriteName} not found in {resourceLocation}");
//dummy texture to prevent null
Texture2D texture = new Texture2D(0, 0);
return Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), Vector2.zero);
}
Your answer
Follow this Question
Related Questions
Unity 2D problem with displaying sprites in final build game 1 Answer
How do I set a sprite to fill the entire screen in UI? 1 Answer
How to recover unused allocated memory? 1 Answer
Override sprite geometry of sprite generated at runtime 1 Answer
How do I get edges to form to the sprite shape and not a block around the sprite? 0 Answers