Okay so i'm new to C# and i made this script. The goal i have in mind is that when the player is on the button and presses a button ( W in this case ) the button is switched from on to off ( or vice versa). The problem i have is that when the character stands on the button and presses W it doesn't always switch its state and i have no idea why. Any info would be appreciated.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Button : MonoBehaviour {
     public bool Pressed = false;
     Animator Anim;

     // Use this for initialization
     void Start () {
         Anim = GetComponent<Animator> ();

     // Update is called once per frame
     void Update () {
         Anim.SetBool ("Pressed", Pressed);
     void OnTriggerStay2D(Collider2D other){
        if (Input.GetKey(KeyCode.W)){
            if (Pressed){
                Pressed = false;
            } else {
                Pressed = true;

As informed by the auto-generated comment, these methods are called at every frame, which means between 60 and 120 times every second approximately.

When you press W, you can be sure it lasts more than 1/100 seconds, which means the bool will switch values many times, and you have 50% chances that in the end you have what you wanted, and 50% chances that you don't.

  • \$\begingroup\$ how would i go about fixing that? \$\endgroup\$ – Insurikai Jan 19 '17 at 17:26
  • \$\begingroup\$ One way would be to know if the key has been released before pressing again. I am not a unity expert but there are methods detecting that for sure, I will let you search that by yourself :) \$\endgroup\$ – realUser404 Jan 19 '17 at 17:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.