获取组件
本课属于 Coddy Unity 学习旅程的“Unity 脚本基础”单元。第 44 课,共 85 课。
GameObject 是一个容器,里面包含组件:Transform、负责绘制它的 MeshRenderer、碰撞体,以及你的脚本。GetComponent<Renderer>()会返回同一个对象上该类型的组件,你的脚本可以通过它改变该组件的行为。transform是现成的 Transform 快捷方式;其他组件都需要你自己获取。
按下 Space 时,这个立方体会变红。它会在Start()中查找一次 Renderer,并将其保存在一个字段中:每次调用GetComponent时,都会搜索对象的组件,而搜索结果不会改变。
Renderer rend;
void Start()
{
rend = GetComponent<Renderer>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
rend.material.color = Color.red;
}
}第一次使用rend.material时,它会为该对象创建一份独立的材质副本,因此其他共享该材质的对象会保留原来的颜色。Unity 为一些颜色提供了名称,例如Color.red、Color.green、Color.blue、Color.yellow和Color.gray;new Color(r, g, b)可以创建其他颜色,每个分量的取值范围都是 0 到 1。
挑战
中等每点击一次,信号灯就会依次亮起:红色、黄色、绿色,然后再次亮起红色。
- 添加一个
Renderer rend;字段,并在Start()中使用GetComponent<Renderer>()设置它。 - 当检测到
Input.GetMouseButtonDown(0)时,将int step字段的值加 1,达到 3 时将它重置为 0。 - 当 step 为 0、1 或 2 时,分别将
rend.material.color设置为Color.red、Color.yellow或Color.green。
按“运行”并点击游戏,信号灯就会改变颜色。然后点击“检查”。
亲手试试
using UnityEngine;
public class SignalLight : MonoBehaviour
{
void Start()
{
}
void Update()
{
// 每点击一次:先变红,再变黄,然后变绿,最后又变红
}
}
Unity 脚本基础中的所有课
自己练习: Unity 在线编辑器