FRP*_*RP7 2 c# colors unity-game-engine
我正在学习C#,Unity我创建了一个简单的游戏,您可以通过单击"C"键(将变为绿色)更改播放器的颜色(默认情况下为红色).代码可以工作,但问题是,我不知道如何创建一个代码,通过使用相同的键("C")再次将绿色更改为红色.我知道的唯一选择是创建另一个if但使用不同的按钮.这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cubecolor : MonoBehaviour {
// Use this for initialization
void Start () {
gameObject.GetComponent<Renderer> ().material.color = Color.red;
}
// Update is called once per frame
void Update () {
if (Input.GetKey(KeyCode.C))
gameObject.GetComponent<Renderer> ().material.color = Color.green;
}
}
Run Code Online (Sandbox Code Playgroud)
您想按C键将颜色更改为红色,然后再次按下以变为绿色.这是非常基本的编程.
每次按下键时,您需要使用布尔变量然后翻转或反转它.通过使用!标志完成翻转.如果布尔变量为true,则使用红色,否则使用绿色.我鼓励您阅读并理解C#中的逻辑运算符和决策.你需要那些才能自己制作一款真正的游戏.
Renderer yourRenderer;
bool red = true;
// Use this for initialization
void Start()
{
yourRenderer = gameObject.GetComponent<Renderer>();
//Use red as default
yourRenderer.material.color = Color.red;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.C))
{
//Flip the boolean variable to the opposite of what it is
red = !red;
//If true, use red color
if (red)
{
yourRenderer.material.color = Color.red;
}
//If false, use green color
else
{
yourRenderer.material.color = Color.green;
}
}
}
Run Code Online (Sandbox Code Playgroud)
不相关,使用GetKeyDown而不是GetKey否则在框架中多次改变颜色时会遇到问题,因此无法看到颜色变化.