- Home /
How to modify unity sprite border by script?
Hi all, is here any way to modify sprite border by script?
I am trying to write a script to modify border parameter with opening Sprite Editor,
but cannot find any Editor API to do that, is it possible?
If not, could I write a function to open Sprite Editor directly?
Answer by Mcsamuel · May 03, 2016 at 04:34 AM
As far as I know you can't. However, you can recreate a sprite and then redefine its border using the Sprite.Create function. Once you have the new sprite you can replace the existing one.
For example if you have an existing sprite simply do something like:
Vector4 newBorder = new Vector4 ( 2, 2, 2, 2);
Rect rect = new Rect( 0,0, oldSprite.texture.width, oldSprite.texture.height);
Sprite newSprite= Sprite.Create(oldSprite.texture, rect, new Vector2(0.5f,0.5f), 100, 1, SpriteMeshType.FullRect, newBorder );
Hopefully this helps you get closer to what you are trying to do.
Answer by UsefulYdyot · Jun 19, 2021 at 01:12 AM
With AssetImporter it works. Got the idea (and main parts of the code) from https://answers.unity.com/questions/943797/editor-script-to-slice-sprites.html
In this example code it works by selecting one ore more sprites in the project window and executing the menu command below.
[MenuItem("Tools/Textures/Modify Sprite Border")]
public static void ModifySpriteBorder()
{
Sprite[] sprites = Selection.GetFiltered<Sprite>(SelectionMode.Deep);
MoveTextureSprites(sprites[0].texture, sprites);
}
static void ModifyTextureSprites(Texture2D texture, Sprite[] sprites)
{
string path = AssetDatabase.GetAssetPath(texture);
var importer = AssetImporter.GetAtPath(path) as TextureImporter;
importer.textureType = TextureImporterType.Sprite;
importer.spriteImportMode = SpriteImportMode.Multiple;
importer.mipmapEnabled = false;
importer.filterMode = FilterMode.Point;
importer.spritePivot = Vector2.down;
importer.textureCompression = TextureImporterCompression.Uncompressed;
TextureImporterSettings textureSettings = new TextureImporterSettings();
importer.ReadTextureSettings(textureSettings);
textureSettings.spriteMeshType = SpriteMeshType.Tight;
textureSettings.spriteExtrude = 0;
string[] spriteNames = new string[sprites.Length];
for (int i = 0; i < sprites.Length; i++)
spriteNames[i] = sprites[i].name;
SpriteMetaData[] spritesheet = importer.spritesheet;
for (int i=0; i<importer.spritesheet.Length; i++)
{
SpriteMetaData data = importer.spritesheet[i];
if (!spriteNames.Contains(data.name))
continue;
// HERE MODIFY data.border
spritesheet[i] = data;
}
importer.spritesheet = spritesheet;
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
return;
}
Not sure, if the importer configuration part is needed.
Your answer
![](https://koobas.hobune.stream/wayback/20220612070317im_/https://answers.unity.com/themes/thub/images/avi.jpg)