Unity3D 场景搭建与灯光交互:按钮控制灯光颜色变化
Unity3D 场景搭建与灯光交互:按钮控制灯光颜色变化
本文将指导您在 Unity3D 中搭建一个包含 Plane、Cube 和两个按钮的场景,并通过脚本控制灯光颜色。您将学习创建灯光、添加按钮事件以及使用 C# 代码实现按钮点击后改变灯光颜色为红色或绿色。
1. 场景搭建
首先,搭建场景,在场景中创建一个 Plane 对象和一个 Cube 对象,并在场景中创建两个按钮对象。
2. 创建脚本并挂载
然后,创建一个 C# 脚本文件,命名为 'light_cont.cs',将其挂载到 Main Camera 对象上。
3. 脚本代码实现
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class light_cont : MonoBehaviour
{
public Light pointLight; // 点光源
public Button redButton; // 红色按钮
public Button greenButton; // 绿色按钮
// Start is called before the first frame update
void Start()
{
// 创建一个黄色点光源,并将其赋值给 Main Camera
pointLight = gameObject.AddComponent<Light>();
pointLight.type = LightType.Point;
pointLight.color = Color.yellow;
pointLight.intensity = 1f;
pointLight.range = 10f;
GetComponent<Camera>().clearFlags = CameraClearFlags.SolidColor;
GetComponent<Camera>().backgroundColor = Color.black;
}
// 点击红色按钮,将光源颜色设置为红色
public void change_red()
{
pointLight.color = Color.red;
}
// 点击绿色按钮,将光源颜色设置为绿色
public void change_green()
{
pointLight.color = Color.green;
}
}
4. 添加按钮事件
最后,在场景中找到两个按钮对象,为其分别添加单击事件响应方法 'change_red()' 和 'change_green()',即可实现运行后创建一个黄色点光源,单击两个按钮分别改变灯光颜色为红色和绿色。
总结
通过以上步骤,您成功搭建了一个包含 Plane、Cube 和两个按钮的场景,并实现了通过按钮点击来改变灯光颜色的功能。这只是一个简单的例子,您可以根据需要扩展和修改代码,实现更复杂的功能。
原文地址: https://www.cveoy.top/t/topic/nAyG 著作权归作者所有。请勿转载和采集!