Unity | Imageの色それぞれ変更する拡張

image.Set単色するための拡張スクリプトを作成しました。

スポンサーリンク

拡張Script

関数(機能)一覧

関数機能戻り値
Image.SetRGBA(float r, float g, float b, float a)RGBAを変更Image
Image.SetRGB(float r, float g, float b)アルファ値を保ったままRGBを変更Image
Image.SetR(float r)ImageのRのみを変更Image
Image.SetG(float g)ImageのGのみを変更Image
Image.SetB(float b)ImageのBのみを変更Image
Image.SetA(float a)ImageのAのみを変更Image

拡張コード

適当なCSファイルに以下のコードを追加します。

using UnityEngine;
using UnityEngine.UI;
namespace BlueBreath.UI
{
    public static class ImageExtension
    {
        public static Image SetRGBA(this Image image, float r, float g, float b, float a)
        {
            image.color = new Color(r, g, b, a);
            return image;
        } 
        public static Image SetRGB(this Image image, float r, float g, float b)
        {
            image.color = new Color(r, g, b, image.color.a);
            return image;
        }        
        public static Image SetR(this Image image, float r)
        {
            image.color = new Color(r, image.color.g, image.color.b, image.color.a);
            return image;
        }
        public static Image SetG(this Image image, float g)
        {
            image.color = new Color(image.color.r, g, image.color.b, image.color.a);
            return image;
        }
        public static Image SetB(this Image image, float b)
        {
            image.color = new Color(image.color.r, image.color.g, b, image.color.a);
            return image;
        }
        public static Image SetA(this Image image, float a)
        {
            image.color = new Color(image.color.r, image.color.g, image.color.b, a);
            return image;
        }
    }
}

デモ・使用方法

デモの使用手順

  1. 拡張Script「ImageExtension」を任意のファイルに導入します
  2. デモコンポーネントを取り付けます
  3. 色を変更するImageコンポーネントへの参照を付けます
using UnityEngine;
using UnityEngine.UI;
using BlueBreath.UI;
namespace BlueBreath.Practice
{
    public class ImageExDemo : MonoBehaviour
    {
        [SerializeField]private Image image;
        // Start is called before the first frame update
        void Start()
        {
            image.SetB(210f/255f).SetG(210f/255f);
        }
    }
}

Tips:メソッドチェーン

返り値が変更したImageですので、続けて他の色を変更することが出来ます。

image.SetB(210f/255f).SetG(210f/255f);

(全色変更する場合は、纏めてしまった方が見やすいかと思います。)

関連・参考

関連

ImageのColor変更が反映されない場合

参考

Image

コメント

タイトルとURLをコピーしました