Question by
JoanneChilds · Mar 06, 2018 at 05:21 PM ·
togglekeypresskeycode
Is it possible to use the keyboards keys like toggle buttons?
I have a 3D map which changes the colour of certain 3D buildings when different keys on the keyboard are pressed. So when the key S is pressed, all the skyscrapers change colour to red. When I press S again, I would like them to go back to their original colour. Is this possible?
void Update () { if (Input.GetKeyDown (KeyCode.S)) { this.GetComponent ().material.color = Color.red; } }
Comment
Best Answer
Answer by andyborrell · Mar 06, 2018 at 09:14 PM
This would do the job:
public class ColorChanger : MonoBehaviour
{
private Color originalColor;
private KeyCode lastKey;
void Start()
{
originalColor = GetComponent<MeshRenderer>().material.color;
}
void CheckForKey(KeyCode key, Color newColor)
{
if (Input.GetKeyDown(key))
{
if (lastKey == key)
{
// This is the key that was pressed last time
// We should put the original color back
GetComponent<MeshRenderer>().material.color = originalColor;
lastKey = KeyCode.None;
}
else
{
// Change to the color specified.
GetComponent<MeshRenderer>().material.color = newColor;
// Remember what key was pressed so that if it pressed again we can toggle back
lastKey = key;
}
}
}
void Update()
{
CheckForKey(KeyCode.R, Color.red);
CheckForKey(KeyCode.G, Color.green);
CheckForKey(KeyCode.B, Color.blue);
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612154033im_/https://answers.unity.com/themes/thub/images/avi.jpg)