1
1

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 1 year has passed since last update.

オブジェクトを発光させる

Posted at

Unityでスクリプトからオブジェクトの色を変更して、オブジェクトが自ら発光するようにします。動作環境はUnity 2022.3.10fです。

Sceneビューを暗くする

光っていることを確認しやすいように次の手順でSceneビューを暗くしておきます。

・Directional Lightを選択してInspectorビューでチェックを外して非アクティブにする。
・Main Cameraを選択してInspectorビューでClear FlagsをDon't Clearに設定する。
・Window→Rendering→Lighting→Environmentを選択してIntensity Multiplierを0にする。

発光するオブジェクトの作成

Hierarchyビューの3D Objectから発光させるためのオブジェクトを作成します。
以下のスクリプトを作成して3Dオブジェクトにアタッチします。

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

public class Emission : MonoBehaviour
{
    void Start()
    {
        this.gameObject.GetComponent<Renderer>().material.EnableKeyword("_EMISSION"); //Emissionを使用できるようにする
        this.gameObject.GetComponent<Renderer>().material.SetColor("_EmissionColor", Color.cyan); //エミッションカラーを指定
        GameObject lightObject = new GameObject("Point Light"); //空のゲームオブジェクトを生成
        Light light = lightObject.AddComponent<Light>(); //空のゲームオブジェクトをライトにする
        light.type = LightType.Point; //ライトの種類を指定
        light.color = Color.cyan; //ライトの色を指定
        lightObject.transform.parent = this.transform; //ライトを子オブジェクトに設定する
        lightObject.transform.localPosition = Vector3.zero; //ライトのローカル座標を親オブジェクトの原点に設定
    }
}

実行すると以下の図のように光ります。
3D ObjectからPlaneを作って発光オブジェクトの下に設置しておくと、光が床に反射しているように見えて、発光していることがわかりやすくなります。

image1.png

オブジェクトを点滅させる

Emission.csを以下のように書き変えることでオブジェクトが点滅するようになります。

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

public class Emission : MonoBehaviour
{
    private GameObject lightObject;
    private Light light;

    void Start()
    {
        this.gameObject.GetComponent<Renderer>().material.EnableKeyword("_EMISSION");
        lightObject = new GameObject("Point Light");
        light = lightObject.AddComponent<Light>();
        light.type = LightType.Point;
        light.color = Color.cyan;
        lightObject.transform.parent = this.transform;
        lightObject.transform.localPosition = Vector3.zero;
    }

    void Update()
    {
        light.intensity = Mathf.PingPong(Time.time * 10, 5); //ライトの明るさを一定周期で変化させる
        this.gameObject.GetComponent<Renderer>().material.SetColor("_EmissionColor", Color.cyan * Mathf.PingPong(Time.time * 2, 1)); //エミッションカラーの明るさを一定周期で変化させる
    }
}

参考

https://edunity.hatenablog.com/entry/20200410/1586448954
https://beginne28949926.com/unity/script-light/

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?