- Home /
How to add a key here?
Hi everybody, can anybody say that how to add a key here. Like, when i will press a key something like e/E then the trigger will be activated. Any help will be appreciated.
private void OnTriggerEnter(Collider other) { triggerCount -= 1; if (triggerCount >= 0 && (other.gameObject.tag == triggerByTag1 || other.gameObject.tag == triggerByTag2)) { if (mute) Camera.main.audio.Stop();
if (playAudio)
{
Camera.main.audio.loop = loop;
Camera.main.audio.clip = playAudio;
Camera.main.audio.volume = musicVolume;
Camera.main.audio.Play();
}
Answer by DiegoSLTS · Jun 21, 2015 at 10:45 PM
To detect keyboard events you have the GetKey, GetKeyDown and GetKeyUp methods, something like this would work for your code example:
if (Input.GetKey(KeyCode.E)) {
//something
}
As for "activating" the trigger, you can call OnTriggerEnter manually if the call in the same script, or make OnTriggerEnter public, but any of those methods is a bad idea. "Activating" a trigger means a collider entered the trigger, but if you force the situation with a key being pressed you don't have a collider.
For me, the best option would be to define another function that has the code you want to run, and call that function from the OnTriggerEnter method or inside the "if (Input.GetKey...)" block. Something like this:
private void OnTriggerEnter(Collider other) {
triggerCount -= 1;
if (triggerCount >= 0 && (other.gameObject.tag == triggerByTag1 || other.gameObject.tag == triggerByTag2)) {
if (mute) Camera.main.audio.Stop();
if (playAudio)
{
PlayAudio();
}
}
}
private void PlayAudio() {
Camera.main.audio.loop = loop;
Camera.main.audio.clip = playAudio;
Camera.main.audio.volume = musicVolume;
Camera.main.audio.Play();
}
//in some other method...
if (Input.GetKey(KeyCode.E)) {
if (audioPlay) {
PlayAudio();
}
}
That's just an example, maybe you want something more inside the PlayAudio method (or whatever you want to call it).
Also, note that GetKey is called during EVERY frame while the E key is held down. If you want a similar behaviour than OnTriggerEnter you should use GetKeyDown, it will be called only once, in the same frame the key changed from not being pressed to being pressed.
Your answer
Follow this Question
Related Questions
How to make a object what can be picked up and when clicked on another object it ends the game? 0 Answers
Using Xbox gamepad triggers as keys instead of axis? 1 Answer
how do i get something to happen when the user presses a key but only inside a trigger? 1 Answer
How do I play an animation with the 'E' key when I enter a trigger 2 Answers
Bow and Arrow (Transporting object) 0 Answers