我想在SpriteRenderer组件中获得GameObject所具有的单个精灵。 不幸的是,这段代码返回了整个地图集,但我需要这部分地图集的一部分。
Texture2D thumbnail = GetComponent<SpriteRenderer>().sprite.texture;
答案 0 :(得分:0)
没有本地API可以从SpriteRenderer
获取单个精灵,也没有API可以按名称访问单个精灵。您可以为此功能投票here。
您可以制作自己的API,以便从Resources
文件夹中的Atlas获取单个精灵,就像问题中包含的图片一样。
您可以使用Resources.LoadAll
从Atlas加载所有精灵,然后将它们存储在字典中。然后可以使用一个简单的函数来访问具有提供名称的每个sprite
。
一个简单的Atlas Loader脚本:
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;
}
}
<强>用法强>:
使用上面的示例图片,&#34; tile &#34;是基本图像,球,底部,人, 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");
}
答案 1 :(得分:-2)
您可以将您需要的图像单独放在Resources文件夹中,然后使用Resources.Load(&#34; spriteName&#34;)来获取它。如果你想把它作为一个精灵,你会做以下事情:
/usr/lib/python2.7/dist-packages/
来源:https://forum.unity3d.com/threads/how-to-change-sprite-image-from-script.212307/
答案 2 :(得分:-2)
使用新的Unity版本,您可以使用SpriteAtlas类和GetSprite方法轻松完成: https://docs.unity3d.com/ScriptReference/U2D.SpriteAtlas.html
因此,如果您正在使用Resources文件夹,则可以执行以下操作:
Resources.Load<SpriteAtlas>("AtlasName")