2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unity】UIの色を変更する【uGUI】

Last updated at Posted at 2019-01-29

こんにちは、電車君です。
今回は、UnityでUIの色を変更する方法を紹介します。

Mathf.Abs(Mathf.Repeat(Time.time, 2f) - 1f);

この記事ではこのコードを使って、時間に対してアルファ値を変更してみたいと思います。
ちなみに、Time.time で取得できる値はゲーム開始からの秒数です。
https://docs.unity3d.com/jp/current/ScriptReference/Time-time.html

追記: Time.time は、 Time.timeScale に影響されるため、
影響されない値を使いたい場合は Time.unscaledTime を使ってください

Graphic.color (Text.color など) を設定する

描画機能を持つuGUIのコンポーネントには、Graphicクラスを継承しています。

Graphicにはcolor変数があり、それを変更することで色を設定する事ができます。

color変数はColorクラスです。
Colorはr,g,bの三原色とaのアルファ値でできており、それらを設定することができます。
https://docs.unity3d.com/ja/2017.4/ScriptReference/Color.html

using UnityEngine;
using UnityEngine.UI;

public class Blinker : MonoBehaviour
{

    public Graphic r;

    void Update()
    {
        var c = r.color;
        c.a = Mathf.Abs(Mathf.Repeat(Time.time, 2f) - 1f);
        r.color = c;
    }
}

これで2秒周期でフェードさせることができます。

CanvasRenderer.SetColor, CanvasRenderer.SetAlpha を使う

実はもっと簡単な方法があります。
Colorでは変数の値をコピーする必要がありますが、
こちらではたった一行で設定することができます。

CanvasRendererは描画機能を持つコンポーネントを表示するために、
必ず付けられているコンポーネントです。
2ecbb62e8450840cf3987ee15c79fd08.png

using UnityEngine;

public class Blinker : MonoBehaviour
{

    public CanvasRenderer r;

    void Update()
    {
        r.SetAlpha(Mathf.Abs(Mathf.Repeat(Time.time, 2f) - 1f));
    }
}

今回は以上です。
バグなどは検証していませんので、
他に方法などがありましたら教えてください。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?