コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】スプライトからスプライトを生成する例

概要

using UnityEngine;

public sealed class Example : MonoBehaviour
{
    [SerializeField] private Sprite         m_sourceSprite;
    [SerializeField] private SpriteRenderer m_spriteRenderer;

    private Sprite m_sprite;

    private void Start()
    {
        var texture = m_sourceSprite.texture;
        var width   = texture.width;
        var height  = texture.height;
        var pivot   = m_sourceSprite.pivot;

        m_sprite = Sprite.Create
        (
            texture: texture,
            rect: new Rect( 0, 0, width, height ),
            pivot: pivot / new Vector2( width, height ),
            pixelsPerUnit: m_sourceSprite.pixelsPerUnit,
            extrude: 0,
            meshType: SpriteMeshType.FullRect
        );

        m_spriteRenderer.sprite = m_sprite;
    }

    private void OnDestroy()
    {
        Destroy( m_sprite );
        m_sprite = null;
    }
}