LoginSignup
38
29

More than 5 years have passed since last update.

【Unity】スクリプトからGameObjectの色を変更する

Last updated at Posted at 2018-04-26

Unityのカラーネームを使う

以下の表の9色はカラーネームが用意されているのでカラーネームを使用することが可能。

カラーネーム 実際の色
black black.PNG
blue blue.PNG
シアン cyan cyan.PNG
灰色 gray または grey gray.PNG
ソリッドグリーン green green.PNG
マゼンダ magenta magenta.PNG
red red.PNG
white white.PNG
yellow yellow.PNG
ChangeColorName.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeColorName : MonoBehaviour {

    // Use this for initialization
    void Start () {
        //オブジェクトの色を赤に変更する
        GetComponent<Renderer>().material.color = Color.red;
    }

    // Update is called once per frame
    void Update () {

    }
}

上記のコードのように GetComponent<Renderer>().material.color = Color.ColorName; で好きな色に変更することができる。

RGBAで指定する

RGBAを用いて指定する。
カラーネーム使用よりも色の幅が広がる。
RGBの各色成分は0~255の範囲で表す。

ChangeColorRGBA.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeColorRGBA : MonoBehaviour {

    // Use this for initialization
    void Start () {
        //オブジェクトの色をRGBA値を用いて変更する
        GetComponent<Renderer>().material.color = new Color32(248, 168, 133, 1);
    }

    // Update is called once per frame
    void Update () {

    }
}

各成分を乱数にしてランダムな色を生成することもできる。

Materialを使う

Unityで作成したMaterialに変更することもできる。
最初にMaterialを宣言し関連付けをする必要があるが他のスクリプトでも同じ色を使用したい場合やスクリプトをいじらずに色を変える場合などには楽。

ChangeColorMaterial.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ChangeColorMaterial : MonoBehaviour {
    public Material colorA;

    // Use this for initialization
    void Start () {
        //オブジェクトの色を用意したMaterialの色に変更する
        GetComponent<Renderer>().material.color = colorA.color;
    }

    // Update is called once per frame
    void Update () {

    }
}
38
29
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
38
29