Home > Back-end >  Button press is being registered twice
Button press is being registered twice

Time:06-03

I'm making a flashlight mechanic that turns on the light when 'F' is pressed and turned off when 'F' is pressed again.

However, when I press the button it registers it twice. I've logged the output of this and the flashlight is turned on and off at the same time.

I know that I must be doing something wrong. What is the best way to solve this issue?

Here is my code:

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

public class Flashlight : MonoBehaviour
{
    public GameObject flashlight;

    public bool lightIsOn;

    void Start()
    {
        lightIsOn = false;
    }

    void Update()
    {
        if (lightIsOn == false)
        {
            if (Input.GetKey(KeyCode.F))
            {
                flashlight.SetActive(true);
                lightIsOn = true;
                Debug.Log("flashlight is on");
            }
        }

        if (lightIsOn == true)
        {
            if (Input.GetKey(KeyCode.F))
            {
                flashlight.SetActive(false);
                lightIsOn = false;
                Debug.Log("Flashlight is off");
            }
        }
    }
}

CodePudding user response:

private bool lightIsOn = false;
void Update()
{
        if (Input.GetKeyDown(KeyCode.F))
        {
            lightIsOn = !lightIsOn;
            flashlight.SetActive(lightIsOn );
            Debug.Log("flashlight is "   lightIsOn);
        }
    }
}

Simply revert the lightIsOn bool on press. Also, use GetKeyDown so that it calls only once when you press

CodePudding user response:

fafase's answer is the recommended way to go, but to explain why your original code was appearing to run twice is because you had two if statements in there instead of an if-else statement.

When the function starts, lightIsOn is equal to false, it then hits your first if statement checking if it is false so it runs the code inside setting lightIsOn to true. However, it then hit your next if statement below it anyway checking if lightIsOn is true and so immediately changing it back to false. Your code would of worked with this slight change:

void Update()
{
    if (lightIsOn == false)
    {
        if (Input.GetKey(KeyCode.F))
        {
            flashlight.SetActive(true);
            lightIsOn = true;
            Debug.Log("flashlight is on");
        }
    }
    else if (lightIsOn == true)
    {
        if (Input.GetKey(KeyCode.F))
        {
            flashlight.SetActive(false);
            lightIsOn = false;
            Debug.Log("Flashlight is off");
        }
    }
}

As it would of only ran one of the conditions. The difference here is the code is told 'Do this OR this' instead of 'do this AND this'. Would still recommend going with fafase's answer though for reasons already given.

  • Related