Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

how can I instantiate bullet prefabs continuously while holding the left mouse button?

I have a bullet prefab that I want to spawn the hole time while holding down the left mouse button and stop spawning when the button is released. However, I am using the new input master system on unity. anyone can help me with that?

my input checker for shooting:

  controls.player.Shoot.performed += ctx => shootOn();
  controls.player.Shoot.canceled += ctx => shootOff();

the methods that I am using with the input:

 void shootOn()
         {
             Instantiate(bullet, firePoint.position, firePoint.rotation);
             shoot = true;
             animator.SetBool("IsShooting", shoot);
         }
     
         void shootOff()
         {
             shoot = false;
             animator.SetBool("IsShooting", shoot);
         }
 
 


Best Answers

  • miangelpmiangelp Member
    Accepted Answer

    Try a boolean

    controls.player.Shoot.performed += ctx => mPressed=true;
    
    controls.player.Shoot.canceled += ctx => mPressed=false;
    
    void Update(){
    if(mPressed){
    //Fire
    }
    }
    


  • jafboyjafboy Member
    edited July 28 Accepted Answer

    thanks @miangelp ! This actually works, but another problem just came up, the bullets are spawning too fast that they collide with each other, is there a way for me to make the bullets spawn at a fixed amount of time?

  • miangelpmiangelp Member
    edited July 28 Accepted Answer
    controls.player.Shoot.performed += ctx => mPressed=true;
    
    controls.player.Shoot.canceled += ctx => mPressed=false;
    
    float fireRate=0.2f;
    
    float timeElapsed;
    
    void Update(){
    
    timeElapsed+=Time.deltaTime;
    
    if(mPressed && timeElapsed>=fireRate){
    
    Instantiate(bullet);
    
    timeElapsed=0;
    
    }
    
    }
    
  • jafboyjafboy Member
    Accepted Answer

    I am very grateful and I appreciate your help, I have been trying to solve this for more than 2 days. Thank you so much @miangelp ! Every thing is working very well.

Answers

  • Use this in the update function

    If(Input.GetMouseButton(0){
       shootOn();
    }else{
       ShootOff();
    }
    
  • jafboyjafboy Member
    edited July 27

    Isn’t there anyway to do it with the new input system? Because if I use the old one, it will return an error that says you have changed the input manager package, so I will have to use the new one. @JIMMY_VASHI04

  • Nah I'm still stuck with the old one cuz i never tried the new input system yet

  • jafboyjafboy Member

    ok @JIMMY_VASHI04 thanks for trying to help! I know that the old one is easier to handle in scripts, but I wanted to learn the new one.

    Again, thank you.@jim

  • miangelpmiangelp Member
    edited July 28

    @jafboy I'm stoked that it worked (: You're welcome!

Sign In or Register to comment.