Background information
Some weeks ago, I start by creating my own platform game. You control a character, that can collect logs and should hold all the campfires on in the game. When the user has collect more then one log, the player have to use this log to hold the fire on. So you should walk to the campfire and should press E to give the log to the fire.
Problem
What the problem momently is, is that when I press the E key
, it will fired the input
more then one time. This is because I use a OnTriggerStay2D
function, to check every second if my Player is collide with the campfire object
.
Do some search on the internet, results in people with the same problem. So one of the solutions was to create an bool
and set it to true on OnTriggerEnter2D
. But this isn't working for me. The same problem as before will occur.
Is there another solution to fix this conflict. When the user press the button, it should be fired ones. Below script is linked to the campfire object.
Also tried it with: if(Input.GetKeyDown(KeyCode.E)) { isTrigger = true; }
and the same for GetKeyUp
, but then isTrigger = false;
My current working code:
public Animator anim;
public int campfireStatus;
bool inTrigger = false;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
anim.SetInteger("Intensity", campfireStatus);
}
void OnTriggerEnter2D(Collider2D other) {
inTrigger = true;
}
void OnTriggerExit2D(Collider2D other) {
inTrigger = false;
}
void OnTriggerStay2D(Collider2D other) {
// If player comes in contact with gameObject
if (other.gameObject.tag=="Player"){
print ("player");
if(Input.GetKeyDown(KeyCode.E)) {
print ("E Pressed");
if (WoodBehaviour.count > 0) {
campfireStatus++;
}
}
}
}
So when the Player
is collide with the campfire object AND the player pressed the E key AND you have more then one logs (this counter will be set in the WoodBehaviour
script, that is linked to the player object ) than it should increase the campfireStatus
with plus one.
The problem is, that the if statements will fired more then one times when pressing the E key.