不能双击

Can't double tap

我有一个问题想不通很久了。如果我在 Unity 中有一个立方体游戏对象,并且我想在按下 space 键时将其颜色更改为红色,我所要做的就是编写一个脚本并写入:

void Update()
{

if (Input.GetKeyDown(KeyCode.Space))
    {
    GameObject Cube = GameObject.FindWithTag("Cube");

    Cube.GetComponent<Renderer>().material.color = Color.red;
    }
}

但是,如果我想在再次按下 space 键时将其颜色更改为蓝色怎么办?

如果你想在第二次点击时改变颜色,你可以简单地添加一个 If-statement 检查颜色是否已经等于想要的颜色,如果它是改变它到另一种颜色。

示例:

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;
    }
}

不相关:

如果具有 Cube Tag 的游戏对象在游戏中保持相同的游戏对象,我建议您宁愿在游戏开始时“获取”游戏对象及其渲染器组件,而不是每次按下space 关键,提高性能。

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 并在更新中检查其值。或者我没看懂问题