うにてぃブログ

UnityやUnreal Engineの記事を書いていきます

【Unity】SpriteRenderer の Inspector拡張

複数選択時に一括で色やアルファを変えられるように

f:id:hacchi_man:20200503001927p:plain:w300

using System.Linq;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(SpriteRenderer))]
[CanEditMultipleObjects]
public class InspectorExtensionSpriteRenderer : Editor
{
    private Editor _editor;
 
    protected SpriteRenderer[] components;
    private Color _color = new Color(); 
    private int _alpha;
     
    private void OnEnable()
    {
        var type = typeof(EditorApplication).Assembly.GetType("UnityEditor.SpriteRendererEditor");
        components = targets.Cast<SpriteRenderer>().ToArray();
        _editor = CreateEditor(targets, type);
    }

    private void OnDisable()
    {
        DestroyImmediate(_editor);
    }
    
    public sealed override void OnInspectorGUI()
    {
        _editor.OnInspectorGUI();
        if (targets.Length <= 1)
            return;
        
        using (var check = new EditorGUI.ChangeCheckScope())
        {
            _color = EditorGUILayout.ColorField("MultiColor", _color);
            if (check.changed)
            {
                foreach (var sr in components)
                {
                    var color = sr.color;
                    for (var i = 0; i < 3; i++)
                        color[i] = _color[i];
                    sr.color = color;
                }
            }
        }
        using (var check = new EditorGUI.ChangeCheckScope())
        {
            _alpha = EditorGUILayout.IntSlider("MultiAlpha", _alpha, 0, 255);
            if (check.changed)
            {
                foreach (var sr in components)
                {
                    var color = sr.color;
                    color.a = _alpha / 255f;
                    sr.color = color;
                }
            }
        }
    }
}