Created
March 15, 2024 01:27
-
-
Save baba-s/2895e0c101fe611c8da3f158700a9dc2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ReSharper disable PossibleLossOfFraction | |
using JetBrains.Annotations; | |
using UnityEngine; | |
namespace Kogane | |
{ | |
/// <summary> | |
/// スプライトをグリッド上に分割して返すクラス | |
/// </summary> | |
public static class SpriteGridSplitter | |
{ | |
//================================================================================ | |
// 関数(static) | |
//================================================================================ | |
/// <summary> | |
/// スプライトをグリッド上に分割して返します | |
/// </summary> | |
[MustUseReturnValue] | |
public static Sprite[] Split | |
( | |
Sprite sprite, | |
int column, | |
int row, | |
SpriteMeshType meshType, | |
float? overridePixelsPerUnit = null | |
) | |
{ | |
var count = column * row; | |
var texture = sprite.texture; | |
var width = texture.width; | |
var height = texture.height; | |
var unitWidth = ( float )width / column; | |
var unitHeight = ( float )height / row; | |
var pivot = sprite.pivot; | |
var pixelsPerUnit = sprite.pixelsPerUnit; | |
var sprites = new Sprite[ count ]; | |
var spriteCount = sprites.Length; | |
for ( var i = 0; i < spriteCount; i++ ) | |
{ | |
var rect = new Rect | |
( | |
x: unitWidth * ( i % column ), | |
y: unitHeight * ( row - 1 - i / column ), | |
width: unitWidth, | |
height: unitHeight | |
); | |
sprites[ i ] = Sprite.Create | |
( | |
texture: texture, | |
rect: rect, | |
pivot: pivot / new Vector2( width, height ), | |
pixelsPerUnit: overridePixelsPerUnit ?? pixelsPerUnit, | |
extrude: 0, | |
meshType: meshType | |
); | |
} | |
return sprites; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment