- Home /
How to use "or" for Keycodes
I'm currently trying to get the following program to play the audio if either of the two keys (Keycode.W and Keycode.S) was pressed, and to stop the audio when the certain key pressed was released. Currently when I run it like it is now, it toggles the sound on/off for only the W key with the S key press just having silence.
public AudioClip robotTurn;
public AudioClip robotMove;
public AudioSource mySource;
// Update is called once per frame
void Update ()
{
var key = KeyCode.W | KeyCode.S; // WRONG should be || not |
if (!Input.GetKey(key))
{
audio.clip = robotMove;
audio.Play ();
mySource.loop = true;
}
if (Input.GetKeyUp(key))
{
audio.clip = null;
}
}
}
or has TWO PIPELINES. ONE pipeline is a totally different operator.
Answer by WillNode · Mar 24, 2015 at 08:03 AM
maybe what are you trying is this :
void Update ()
{
if (!(Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.S)))
{
audio.clip = robotMove;
audio.Play ();
mySource.loop = true;
}
if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.S))
{
audio.clip = null;
}
}
it's better to use Input.GetButton()
instead if you want to set two keys at a time, but depends on your question, hope this answer help you.
Answer by Andres-Fernandez · Mar 24, 2015 at 08:02 AM
There are several ways of doing that (using a list of keycodes to be allowed to start the sound and detect any key press, for example). But the easiest that comes to my mind is just using a bit of logic to control which key is pressed (knowing that you only use those two keys):
You need to keep track of the key that triggered the sound and also the state of the clip being played:
private bool isPlaying = false;
private KeyCode soundTrigger;
void Update() {
if (Input.GetKeyDown(KeyCode.W) && !isPlaying) {
soundTrigger = KeyCode.W;
isPlaying = true;
PlayMyClip();
}
if (Input.GetKeyDown(KeyCode.S) && !isPlaying) {
soundTrigger = KeyCode.S;
isPlaying = true;
PlayMyClip();
}
if (Input.GetKeyUp(KeyCode.W) && isPlaying && soundTrigger == KeyCode.W) {
audio.clip = null;
isPlaying = false;
}
if (Input.GetKeyUp(KeyCode.S) && isPlaying && soundTrigger == KeyCode.S) {
audio.clip = null;
isPlaying = false;
}
}
void PlayMyClip() {
audio.clip = robotMove;
audio.Play();
mySource.loop = true;
}
Haven't tested the code, but the logic can be something similar to this one. Also, this isn't scalable at all, but it can work in this case.
Your answer
![](https://koobas.hobune.stream/wayback/20220613191102im_/https://answers.unity.com/themes/thub/images/avi.jpg)