うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【Unity】Image の Outline っぽいものを作成する

BaseMeshEffect を用いて同じ画像をスケールを変えて複製することで Outline っぽいものを再現しています

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
[RequireComponent(typeof(Image))]
public class OutlineImage : BaseMeshEffect
{
    [SerializeField]
    private float _length = 1f;
    [SerializeField]
    private Color _color = Color.black;
     
    private readonly List<UIVertex> _vertexList = new List<UIVertex>();
 
    public override void ModifyMesh(VertexHelper helper)
    {
        _vertexList.Clear();
        helper.GetUIVertexStream(_vertexList);
 
        var count = _vertexList.Count;
         
        var max = _vertexList[0].position;
        var min = _vertexList[0].position;
 
        for (var i = 1; i < count; i++)
        {
            for (var j = 0; j < 2; j++)
            {
                if (max[j] < _vertexList[i].position[j])
                    max[j] = _vertexList[i].position[j];
                if (min[j] > _vertexList[i].position[j])
                    min[j] = _vertexList[i].position[j];
            }
        }
         
        var center = (min + max) / 2f;
         
        for (var i = 0; i < count; i++)
        {
            var vertex = _vertexList[i * 2];
            var toOutside = (vertex.position - center).normalized;
            vertex.position += toOutside * _length;
            vertex.color = _color;
            _vertexList.Insert(i, vertex);
        }
         
        helper.Clear();
        helper.AddUIVertexTriangleStream(_vertexList);
    }
}