参考サイト様
ソースコード(引用)
using System;
using System.Linq;
using UnityEngine;
public class Example : MonoBehaviour
{
public GameObject filler;
public Vector2 fillerSize = Vector2.one * 0.5f;
public Vector2 spacing = Vector2.one * 0.1f;
public SpriteRenderer spriteRenderer;
[ContextMenu(nameof(Test))]
private void Test()
{
var sprite = spriteRenderer.sprite;
var texture = sprite.texture;
var worldBounds = spriteRenderer.bounds;
var pixelRect = sprite.rect;
var fillerSizeFactor = Vector2.one / worldBounds.size * pixelRect.size;
var fillerSizeInPixels = Vector2Int.RoundToInt(fillerSize * fillerSizeFactor);
var start = worldBounds.min;
var end = worldBounds.max;
for (var worldY = start.y; worldY < end.y; worldY += fillerSize.y + spacing.y)
{
var pixelY = Mathf.RoundToInt((worldY - worldBounds.center.y + worldBounds.size.y / 2f) * fillerSizeFactor.y);
if (pixelY + fillerSizeInPixels.y >= texture.height)
{
continue;
}
for (var worldX = start.x; worldX < end.x; worldX += fillerSize.x + spacing.x)
{
var pixelX = Mathf.RoundToInt((worldX - worldBounds.center.x + worldBounds.size.x / 2f) * fillerSizeFactor.x);
if (pixelX + fillerSizeInPixels.x >= texture.width)
{
continue;
}
var pixels = texture.GetPixels(pixelX, pixelY, fillerSizeInPixels.x, fillerSizeInPixels.y);
if (pixels.All(p => Mathf.Approximately(p.a, 0f)))
{
continue;
}
Instantiate(filler, new Vector3(worldX, worldY, 0), Quaternion.identity, transform);
}
}
}
}