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

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;
}