Run script once after button is held for certain time?

I’m new to coding, and I’m working on a particle for a charge shot. I want the particle to trigger once after the shoot button has been held for 2 seconds, to indicate that it’s charged. The solution I have here kind of works. It does what I want when you only shoot once. It shoots the normal bullet, and 2 seconds later it triggers the particle.

if (Input.GetKeyDown("space"))
        {
            totalCharge = 0f;
            GameObject Bullet = Instantiate(BulletPrefab, transform.position, transform.rotation);
            Bullet.GetComponent<Rigidbody2D>().AddRelativeForce(Vector2.up * bulletForce);
            ParticleThing();
            Destroy(Bullet, 1.5f);
          
        }
public void ParticleThing()
    {
       
        if (Input.GetKey(chargeAndShootKey))
        {
           
            StartCoroutine(ChargeParticle());
        }
       

    }
   public IEnumerator ChargeParticle()
    {
      
        yield return new WaitForSeconds(2);
        if (Input.GetKey(chargeAndShootKey))
            {
               
                Debug.Log("Play particle");
                Charge.transform.position = gameObject.transform.position;
                Charge.Play();
                yield return new WaitForSeconds(1);
              
               
            }
      
    }

The issue with this is that if you spam shoot, (let’s say 3 times) THEN hold it down, the particle also triggers for all the times you pressed shoot before you began holding it.
I want it to only trigger once for the time you actually began holding the button down. Is there a way to achieve this?

You will want to create a timer. If the button is being held down, the timer counts down from 2. If the button is released, you reset the timer back to 2. But if the button is being held down, and then the timer hits 0, then you can call your shoot function.

Better to do this in update. Pseudocode:

  • check if key was pressed this frame

  • set timer variable to Time.deltaTime

  • else if key is pressed

  • add Time.deltaTime to timer variable

  • else

  • set timer variable to 0

    • if timer exceeds 2s
  • KABLOOOM!

  • set timer variable to 0