问题描述
我有一个问题,我很长一段时间无法弄清楚自己。如果我在Unity中有一个多维数据集游戏对象,并且想在按空格键时将其颜色更改为红色,那么我所要做的就是编写脚本并编写:
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
GameObject Cube = GameObject.FindWithTag("Cube");
Cube.GetComponent<Renderer>().material.color = Color.red;
}
}
但是如果我想再次按空格键时将其颜色更改为蓝色怎么办?
解决方法
如果要在第二次单击时更改颜色,则只需添加一个If语句,即可检查该颜色是否已经与所需颜色相等,以及是否已将其更改为另一种颜色。
示例:
if (Input.GetKeyDown(KeyCode.Space)) {
// Get Cube GameObject
GameObject Cube = GameObject.FindWithTag("Cube");
// Get the Cube Renderer
Renderer rd = Cube.GetComponent<Renderer>();
// Is the color equal to red if it already is,// change it to blue instead
if (rd.material.color = Color.red) {
rd.material.color = Color.blue;
}
else {
rd.material.color = Color.red;
}
}
不相关:
如果具有多维数据集标签的GameObject在游戏中保持相同的GameObject,我建议您在游戏开始时宁愿“获取” GameObject及其渲染器组件,而不必每次按空格键,以提高性能。
private GameObject cubeGO;
private Renderer cubeRD;
private void Start {
// Get Cube GameObject
cubeGO = GameObject.FindWithTag("Cube");
// Get the Cube Renderer
cubeRD = Cube.GetComponent<Renderer>();
}
您现在可以在Input.GetKeyDown(){}
if (Input.GetKeyDown(KeyCode.Space)) {
// Is the color equal to red if it already is,// change it to blue instead
if (cubeRD.material.color = Color.red) {
cubeRD.material.color = Color.blue;
}
else {
cubeRD.material.color = Color.red;
}
}
,
例如,您可以使用变量is_red
并在更新中检查其值。也许我不明白问题所在