I have a set of objects that grow/shrink in different directions.
The only way I’ve found how to do this is to set the pivot of the sprite and then scale x and y accordingly. As of right now I have a bunch of sprite prefabs saved with pivot positions set to multiple points on the sprite depending on how I want the object to grow.
I would like to instead be able to programmatically set the pivot of the sprite via C# script so that I may instantiate a sprite at run time (level load) and use it as needed. This seems to be a cleaner more elegant way of doing things.
However, I have no idea how I would go about doing such a thing. All questions that have been asked similar to this one have been ended with an answer to use the Sprite Editor.
Any ideas?
Thanks.
There seems to be many different solutions for this.
Option 1:
You can make a prefab consisting of an empty root object and a child object with a sprite renderer:
-----> HandleObject (root, empty)
----------> SpriteObject (child, with sprite renderer)
Then by positioning the SpriteObject on different places you will get different behaviour when scaling the HandleObject. You can set the position of the SpriteObject manually in editor, or then you can do it by code, using your own created algorithm that positions it correctly for your intended behaviour. This certainly needs some trial and error before getting it correct.
Option 2:
You could instead use the Image component of Unity’s UI system and having the Canvas set to World Space. With the UI system you then have access to the pivot property of the RectTransform component.
Option 3:
By looking at the docs you can see that the Sprite class has a static function called Sprite.Create Unity - Scripting API: Sprite.Create With this you can make your own sprite at run-time by specifying its texture, pivot etc. I cannot say what this means in terms of garbage, but I assume you haven’t addressed this as much since you are using Instantiate instead of an Object Pool.
I made a tool for setting the Sprite pivot points in the editor while maintaining their world positions: GitHub - thepowerprocess/UnitySpritePivotEditor: Easily edits a 2D Sprite while maintaining its position
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();