- Home /
How can I programatically set the SpriteMeshType of sprites?
Hey
I have a lot of sprites to import, so have written a script using TextureImportSettings so set the size, filter mode etc. The problem I am facing is that the mesh type (tight/rect) can only be set using Sprite.Create(...), I like it to be Rect rather than the default Tight.
How can I load all my sprites, recreate them with the new SpriteMeshType and then save them out?
Here's my code so far:
...create all our meta data etc
textureImporter.spritesheet = spiteMetaData.ToArray();
textureImporter.SaveAndReimport();
AssetDatabase.Refresh();
string spriteSheet = AssetDatabase.GetAssetPath(theTexture);
Sprite[] sprites = AssetDatabase.LoadAllAssetsAtPath(spriteSheet).OfType<Sprite>().ToArray();
for (int x = 0; x < sprites.Length; x++)
{
sprites[x] = Sprite.Create(theTexture, sprites[x].rect, sprites[x].pivot, 1, 2, SpriteMeshType.FullRect);
// Save sprite here?
}
// Or reassign the sprites here?
I think my major hurdle is that it's a bit confusing how sprite data is saved with the texture. You create a bunch of SpriteMetaData, but you get Sprites back. So when you load a sprite, it's created on the fly from the texture and the sprite meta data? If that's the case, how do you set the SpriteMeshType?
I'm unable to see how to save the sprites through any AssetDatabase functions or anything.
Thanks
Answer by talecrafter · Apr 01, 2017 at 07:32 AM
Hi. You can set the SpriteMeshType through SetTextureSettings on the TextureImporter. Here is some sample code from my own utilities.
public static bool SetTexture2DSpriteMeshType(ref Texture2D texture, SpriteMeshType meshType)
{
if (texture == null)
{
return false;
}
string assetPath = AssetDatabase.GetAssetPath(texture);
TextureImporter importer = AssetImporter.GetAtPath(assetPath) as TextureImporter;
if (importer == null)
{
return false;
}
TextureImporterSettings textureSettings = new TextureImporterSettings();
importer.ReadTextureSettings(textureSettings);
if (textureSettings.spriteMeshType != meshType)
{
textureSettings.spriteMeshType = meshType;
importer.SetTextureSettings(textureSettings);
importer.SaveAndReimport();
return true;
}
return false;
}
Perfect! This seems to be undocumented and has been logged as an issue.
But "TextureImporterSettings" only works in editor not build
So this is another way without using TextureImporterSettings
Texture2D tex2d = new Texture2D (GetComponent<Image> ().mainTexture.width, GetComponent<Image> ().mainTexture.height);
tex2d = GetComponent<Image> ().mainTexture as Texture2D;
GetComponent<Image> ().sprite = Sprite.Create (tex2d, GetComponent<Image> ().sprite.rect, new Vector2 (0.5f, 0.5f),100,0,Sprite$$anonymous$$eshType.FullRect);