Unity ボタンの中にimageを追加したがクリックした時の色が気に入らない...


ボタンの中に追加した画像の色がクリック時に変わらない

Unityでボタンの中に image を追加したが、ボタンを押した時に、追加した image の色が変わらない...。
なんか画像が浮いてる...。

これは困った...と、ググってみたら...。

UGUI; Multi image button transition
http://answers.unity3d.com/questions/820311/ugui-multi-image-button-transition.html

なるほど、これは良さげだなと...今回、組み込んでみた内容を記録してみました。

MultiImageButton.csを作成

まず、MultiImageButton.csを作成しましたが、自分はGraphicsプロパティでm_graphicsへ代入する式を変更しました(ボタン自身の子供を指定)。

MultiImageButton.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.UI;
using UnityEngine.EventSystems;


/**
 * 参考にした URL
 * http://answers.unity3d.com/questions/820311/ugui-multi-image-button-transition.html
 */
public class MultiImageButton : Button
{
    private Graphic[] m_graphics;
    protected Graphic[] Graphics
    {
        get
        {
            if (this.m_graphics == null)
            {
                //変更点 ボタンオブジェクト以下の子オブジェクトを対象としました。
                this.m_graphics = targetGraphic.transform.GetComponentsInChildren<Graphic>();
            }

            return this.m_graphics;
        }
    }


    protected override void DoStateTransition (SelectionState state, bool instant)
    {
        Color color;
        switch (state)
        {
            case (Selectable.SelectionState.Normal):
                color = this.colors.normalColor;
                break;

            case (Selectable.SelectionState.Highlighted):
                color = this.colors.highlightedColor;
                break;

            case (Selectable.SelectionState.Pressed):
                color = this.colors.pressedColor;
                break;

            case (Selectable.SelectionState.Disabled):
                color = this.colors.disabledColor;
                break;

            default:
                color = Color.black;
                break;
        }

        if (base.gameObject.activeInHierarchy)
        {
            switch (this.transition)
            {
                case (Selectable.Transition.ColorTint):
                    this.ColorTween(color * this.colors.colorMultiplier, instant);
                    break;

                default:
                    throw new System.NotSupportedException();
            }
        }
    }


    private void ColorTween(Color targetColor, bool instant)
    {
        if (this.targetGraphic == null)
        {
            return;
        }

        foreach (var g in this.Graphics)
        {
            g.CrossFadeColor(targetColor, (!instant) ? this.colors.fadeDuration : 0f, true, true);
        }
    }
}

ボタンのスクリプトを差し替え

ボタンの「Button (Script)」を「MultiButton (Script)」に差し替えます。

いったんボタンから「Button (Script)」コンポーネントを削除し...

ボタンの[Add Component]から「Multi Image Button (Script)」コンポーネントを追加しました。

追加した「Multi Image Button (Script)」の設定は以前と同じように設定可能みたいです。

動作確認

デバッグしてみると、押したときの違和感がなくなりました。
(例だとわかりづらいですが...)