用C#实现搭建包含一个Plane对象、一个 Cube对象和两个按钮对象的场景。阅读理解以下代码编写脚本 light contcs挂载到Main Camera 上为两个按钮对象分别添加单击事件响应方法 change _red和 change_green实现运行后创建一个黄色点光源单击两个按钮分别改变灯光颜色为红色和绿色
场景搭建:
- 在场景中创建一个 Plane 对象和一个 Cube 对象
- 在 Canvas 中创建两个按钮对象,命名为 RedButton 和 GreenButton
light_cont.cs 代码:
using UnityEngine;
using UnityEngine.UI;
public class light_cont : MonoBehaviour
{
public GameObject lightObj; // 光源对象
private Light lightComponent; // 光源组件
// Start is called before the first frame update
void Start()
{
// 获取光源组件
lightComponent = lightObj.GetComponent<Light>();
// 设置光源颜色为黄色
lightComponent.color = Color.yellow;
// 获取按钮组件,并添加监听方法
Button redButton = GameObject.Find("RedButton").GetComponent<Button>();
redButton.onClick.AddListener(change_red);
Button greenButton = GameObject.Find("GreenButton").GetComponent<Button>();
greenButton.onClick.AddListener(change_green);
}
// 点击红色按钮
void change_red()
{
// 设置光源颜色为红色
lightComponent.color = Color.red;
}
// 点击绿色按钮
void change_green()
{
// 设置光源颜色为绿色
lightComponent.color = Color.green;
}
}
将该脚本挂载到 Main Camera 上即可。在运行时,点击 RedButton 可以将光源颜色改变为红色,点击 GreenButton 可以将光源颜色改变为绿色
原文地址: https://www.cveoy.top/t/topic/cRsZ 著作权归作者所有。请勿转载和采集!