- Home /
Change Sprite Pivot/Bounds from Script
I searched all over the place (Google, Forums, here at Answers) with no luck, so excuse me if this is already answered (somewhere).
I would like to change the pivot of a Sprite through scripting.
So normally I would write:
Sprite sprite; // some sprite reference
sprite.bounds.center = Vector2.zero; // the preferable pivot
Or if there was a "pivot" set method like
sprite.SetPivot(Vector2.zero); // or something similar
Since sprite.bounds is property AND readonly it cannot be assigned (Even if I create a new Bounds variable). There is not even a setter property in Sprite class to do the job, so my question is, is there a way to change sprite's pivot through scripting?
Thank you.
From reading the script reference, the only way I could see to change the anchor is to use Sprite.Create() to create a new sprite from a texture.
I don't think that would solve the problem (sort of). It would lose batching and that would be ugly... After hours of searching, still nothing.
Answer by robertbu · Feb 10, 2014 at 04:41 AM
I don't know how much of the Sprite technology you need. You could make the sprite a child of an empty game object and use localPosition to change the anchor. You could also roll your own sprite using a Quad, or there are third-party solutions. Sorry I cannot be more helpful.
Answer by Lttldude · Dec 06, 2020 at 05:22 AM
I made a tool for setting the Sprite pivot points in the editor while maintaining their world positions: https://github.com/thepowerprocess/UnitySpritePivotEditor
This is the part where the sprite texture is edited:
SpriteRenderer sr = selectedGameObject.GetComponent<SpriteRenderer>();
string path = AssetDatabase.GetAssetPath(sr.sprite.texture);
TextureImporter ti = (TextureImporter)AssetImporter.GetAtPath(path);
Vector2 newPivot = new Vector2(childMousePos.x / (sr.sprite.texture.width / sr.sprite.pixelsPerUnit), childMousePos.y / (sr.sprite.texture.height / sr.sprite.pixelsPerUnit)) + ti.spritePivot;
ti.spritePivot = newPivot;
TextureImporterSettings texSettings = new TextureImporterSettings();
ti.ReadTextureSettings(texSettings);
texSettings.spriteAlignment = (int)SpriteAlignment.Custom;
ti.SetTextureSettings(texSettings);
ti.SaveAndReimport();