问题描述
我想获得一个单一的精灵,GameObject在SpriteRenderer组件中具有该精灵。
不幸的是,这段代码返回了整个地图集,但我需要其中一部分。
Texture2D thumbnail = GetComponent< SpriteRenderer>()。sprite.texture;
没有本地API从 SpriteRenderer
获取单个Sprite,也没有API可以按名称访问单个Sprite。您可以为此功能投票
在上面的示例图片中, tile 是基本图片, ball ,底部, people 和 wallframe 是精灵
void Start()
{
AtlasLoader atlasLoader = new AtlasLoader( tiles );
Debug.Log( Atlas Count: + atlasLoader.atlasCount());
Sprite ball = atlasLoader.getAtlas( ball);
Sprite bottom = atlasLoader.getAtlas( bottom);
Sprite people = atlasLoader.getAtlas( people);
Sprite wallframe = atlasLoader.getAtlas( wallframe);
}
I'd like to get a single sprite which GameObject has in a SpriteRenderer component.Unfortunately, this code returns the whole atlas, but I need to a part of this atlas.
Texture2D thumbnail = GetComponent<SpriteRenderer>().sprite.texture;
There is no native API to get single sprite from the SpriteRenderer
and no API to access individual Sprite by name. You can vote for this feature here.
You can make your own API to get single sprite from Atlas located in the Resources
folder like the image included in your question.
You can load all the sprites from the Atlas with Resources.LoadAll
then store them in a dictionary.A simple function can then be used to access each sprite
with the provided name.
A simple Atlas Loader script:
public class AtlasLoader
{
public Dictionary<string, Sprite> spriteDic = new Dictionary<string, Sprite>();
//Creates new Instance only, Manually call the loadSprite function later on
public AtlasLoader()
{
}
//Creates new Instance and Loads the provided sprites
public AtlasLoader(string spriteBaseName)
{
loadSprite(spriteBaseName);
}
//Loads the provided sprites
public void loadSprite(string spriteBaseName)
{
Sprite[] allSprites = Resources.LoadAll<Sprite>(spriteBaseName);
if (allSprites == null || allSprites.Length <= 0)
{
Debug.LogError("The Provided Base-Atlas Sprite `" + spriteBaseName + "` does not exist!");
return;
}
for (int i = 0; i < allSprites.Length; i++)
{
spriteDic.Add(allSprites[i].name, allSprites[i]);
}
}
//Get the provided atlas from the loaded sprites
public Sprite getAtlas(string atlasName)
{
Sprite tempSprite;
if (!spriteDic.TryGetValue(atlasName, out tempSprite))
{
Debug.LogError("The Provided atlas `" + atlasName + "` does not exist!");
return null;
}
return tempSprite;
}
//Returns number of sprites in the Atlas
public int atlasCount()
{
return spriteDic.Count;
}
}
Usage:
With the Example image above, "tile" is the base image and ball, bottom, people, and wallframe are the sprites in the atlas.
void Start()
{
AtlasLoader atlasLoader = new AtlasLoader("tiles");
Debug.Log("Atlas Count: " + atlasLoader.atlasCount());
Sprite ball = atlasLoader.getAtlas("ball");
Sprite bottom = atlasLoader.getAtlas("bottom");
Sprite people = atlasLoader.getAtlas("people");
Sprite wallframe = atlasLoader.getAtlas("wallframe");
}
这篇关于从Sprite Atlas获取单个Sprite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!