c# - 如何在 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);
}
}
解决方案
您只需要在脚本中获取对点光源的引用并更改其颜色,就像您为渲染器的材质所做的那样。
您的脚本可以改进很多,但只需进行少量更改,如下所示:
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;
}
}
推荐阅读
- android - Mockito-Kotlin 异常:UnfinishedStubingException
- python - 通过volume和pymysql连接MYSQL容器和Python容器
- python - 程序将我发送到错误功能,如何将其更改为 ItayVAT?
- ios - 如何在 iPhone iOS 的设置中查看 Safari 版本?
- .net-core - Dotnet 核心 3.1 身份服务器缺少 Newtonsoft.Json 12.0.0
- python - 如何在 Python 中将日期格式 (YYYY-MM-DD) 转换为 (YYYY,MM,DD)
- angular - Angular Material mat-select 重用 mat-option
- ios - Swift:For循环一一同步,直到所有函数响应
- c++ - 将模板类转换为头文件和 cpp 文件
- xml - 无法读取配置部分“system.webserver”,因为它缺少部分声明