Shot is activated only when I walk.

Hello everyone.

I’m trying to understand the problem in this script. When the character walks the shot works but when the character is still the shot is not working.

This is the script:

#pragma strict
 
var Prefab : Rigidbody2D;
var PrefabSpeed : float = 8;

function Update () 
{
 
 if(Input.GetButtonDown("Fire1")) 
{
  
   if(Collisions.GRENADE_AMMO <= 0) 
 
         
        if(!Prefab || !PrefabSpeed)
    
     
  else
  
   {
        if (Input.GetKey(KeyCode.D))
       { 
        var PrefabCreate = Instantiate(Prefab,GameObject.Find("Projectile Spawn").transform.position,Quaternion.identity);
        PrefabCreate.rigidbody2D.velocity = transform.TransformDirection(Vector2.right * PrefabSpeed); 
       } 
        if (Input.GetKey(KeyCode.A))
        {
        PrefabCreate = Instantiate(Prefab,GameObject.Find("Projectile Spawn").transform.position,Quaternion.identity);
        PrefabCreate.rigidbody2D.velocity = transform.TransformDirection(-Vector2.right * PrefabSpeed); 
      }
     }

You have many if without brackets or action assigned on it and you seems to instatiate your bullets in movement key conditions.

It should looks like this:

if(Input.GetButtonDown("Fire1")) 
{
   //fire action
}
  if (Input.GetKey(KeyCode.D)) 
{
   //move right action
}
         
 if (Input.GetKey(KeyCode.A)) 
{
    //move left action
}

Hello barbe63.

The problem now that fires 10 rounds together when it enters boxcollider2D. 10 shots fired all together, both right and left.

I show you the code:

#pragma strict
 
var Prefab : Rigidbody2D;
var PrefabSpeed : float = 8;
//var PrefabCreate = Vector2.right;

static var myObject : GameObject; 



function Update () 
{
 


 if(Input.GetButtonDown("Fire1")) 
{
   }
   if (Input.GetKey(KeyCode.D)) 
 {
    //move right action
 }
          
  if (Input.GetKey(KeyCode.A)) 
 {
     //move left action
 }    
   
   if(Collisions.GRENADE_AMMO <= 0) 
  {
      myObject.SetActive(false);
  } 
         
        if(!Prefab || !PrefabSpeed)
    
      {
            Debug.Log("Il prefab o la velocità non esiste");
      }
      
  else
  
   {
       
         //if (Input.GetKey(KeyCode.D))
        
        var PrefabCreate = Instantiate(Prefab,GameObject.Find("Projectile Spawn").transform.position,Quaternion.identity);
        PrefabCreate.rigidbody2D.velocity = transform.TransformDirection(Vector2.right * PrefabSpeed); 
        
        //if (Input.GetKey(KeyCode.A))
        
        PrefabCreate = Instantiate(Prefab,GameObject.Find("Projectile Spawn").transform.position,Quaternion.identity);
        PrefabCreate.rigidbody2D.velocity = transform.TransformDirection(-Vector2.right * PrefabSpeed); 
      
     
     
     
     Collisions.GRENADE_AMMO --;
     GameObject.Find("g_Count").guiText.text = ""+Collisions.GRENADE_AMMO;
     print("YOU NOW HAVE " + Collisions.GRENADE_AMMO + " GRENADES");
     }
   }
//}