首页 > 解决方案 > 如何在 Unity 中控制点光源的颜色?

问题描述

我已经设法将一种材料应用于网格,随着时间的推移不断地改变颜色(从一组颜色中挑选出来),我想对点光源做同样的事情。我怎样才能做到这一点?

颜色

这是控制材质颜色的脚本,我想对其进行调整,因此它也可以控制灯光的颜色。

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

public class ChangeColors : MonoBehaviour
{
    public Color[] colors;

    public int currentIndex = 0;
    private int nextIndex;

    public float changeColourTime = 2.0f;

    private float lastChange = 0.0f;
    private float timer = 0.0f;

    void Start()
    {
        if (colors == null || colors.Length < 2)
            Debug.Log("Need to setup colors array in inspector");

        nextIndex = (currentIndex + 1) % colors.Length;
    }

    void Update()
    {

        timer += Time.deltaTime;

        if (timer > changeColourTime)
        {
            currentIndex = (currentIndex + 1) % colors.Length;
            nextIndex = (currentIndex + 1) % colors.Length;
            timer = 0.0f;

        }
        GetComponent<Renderer>().material.color = Color.Lerp(colors[currentIndex], colors[nextIndex], timer / changeColourTime);
    }
}

标签: c#unity3d

解决方案


您只需要在脚本中获取对点光源的引用并更改其颜色,就像您为渲染器的材质所做的那样。

您的脚本可以改进很多,但只需进行少量更改,如下所示:

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

public class ChangeColors : MonoBehaviour
{
    public Color[] colors;
    public Light pLight;

    public int currentIndex = 0;
    private int nextIndex;

    public float changeColourTime = 2.0f;

    private float lastChange = 0.0f;
    private float timer = 0.0f;

    void Start()
    {
        if (colors == null || colors.Length < 2)
            Debug.Log("Need to setup colors array in inspector");

        nextIndex = (currentIndex + 1) % colors.Length;
    }

    void Update()
    {

        timer += Time.deltaTime;

        if (timer > changeColourTime)
        {
            currentIndex = (currentIndex + 1) % colors.Length;
            nextIndex = (currentIndex + 1) % colors.Length;
            timer = 0.0f;

        }
        Color c = Color.Lerp(colors[currentIndex], colors[nextIndex], timer / changeColourTime);
        GetComponent<Renderer>().material.color = c; // MIND! you should store the Renderer reference in a variable rather than getting it once per frame!!!
        pLight.color = c;
    }
}

unity 改变点灯光颜色


推荐阅读