Tolga Yavuz
Tolga Yavuz

Reputation: 159

Is there anyway to set pivot of sprite with script?

We recieve a psd files from our designers for objects. We are working on an isometric 2.5D game, sprites are half-3D renders. We got 2 layers on PSD files, one is for ground (we use that as obstacle with polygon 2d collider) and other layer is building/object. For accurate sprite render order we have to put pivot point of the building/object to ground-level. When we did import PSD to Unity, the pivot points of layers are automaticly at the center of image. We need to set pivot point of sprite to ground level same as ground-layer's pivot.

Is there anyway to achieve this? Looks like "Sprite.pivot" is read-only can't changable via script.

Upvotes: 4

Views: 5233

Answers (2)

The.Power.Process
The.Power.Process

Reputation: 450

I made a tool for setting the Sprite pivot points in the editor while maintaining their world positions: https://github.com/thepowerprocess/UnitySpritePivotEditor

enter image description here

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();

Upvotes: 4

derHugo
derHugo

Reputation: 90683

You could create a new Sprite from the existing one and alter the pivot point using Sprite.Create

public Sprite CreateSpriteWithPivot(Sprite existingSprite, Vector2 pivot)
{
    return Sprite.Create(existingSprite.texture, existingSprite.rect, pivot);
}

 

Upvotes: 7

Related Questions