Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Reloading ONLY when pressing "R"

Discussion in 'Scripting' started by hattyh, Aug 5, 2015.

  1. hattyh

    hattyh

    Joined:
    Jul 8, 2015
    Posts:
    15
    1. Code (CSharp):
      1. using UnityEngine;
      2. using System.Collections;
      3. using System.Collections.Generic;
      4.  
      5. public class Gun : MonoBehaviour
      6. {
      7.  
      8.     Animator animator;
      9.  
      10.     public enum weaponType { Shotgun, Machinegun, Burst, Launcher }; // use burst for single shot weapons like pistols / sniper rifles
      11.     public weaponType typeOfGun;
      12.  
      13.     public enum LauncherType { Grenade, Rocket }; // Type of launcher
      14.     public LauncherType typeOfLauncher;
      15.  
      16.     public enum BulletType { Physical, Raycast }; // physical bullets of raycasts
      17.     public BulletType typeOfBullet;
      18.    
      19.  
      20.     // basic weapon variables all guns have in common
      21.     // Objects, effects and tracers
      22.     public GameObject bullet = null;        // the weapons bullet object
      23.     public GameObject grenade = null;       // the grenade style round... this can also be used for arrows or similar rounds
      24.     public GameObject rocket = null;        // the rocket round
      25.     public Renderer muzzleFlash = null;     // the muzzle flash for this weapon
      26.     public Light lightFlash = null;         // the light flash for this weapon
      27.     public Transform muzzlePoint = null;    // the muzzle point of this weapon
      28.     public Transform ejectPoint = null;     // the ejection point
      29.     public Transform mountPoint = null;     // the mount point.... more for weapon swapping then anything
      30.     public Rigidbody shell = null;          // the weapons empty shell object
      31.     public GameObject gunOwner = null;      // the gun owner
      32.     public GameObject mainCamera = null;    // the player's main camera
      33.     public GameObject weaponCamera = null;  // this weapon's camera
      34.     public GameObject impactEffect = null;  // impact effect, used for raycast bullet types
      35.     public GameObject bulletHole = null;    // bullet hole for raycast bullet types
      36.  
      37.     public GameObject weaponTarget = null;
      38.  
      39.     //Machinegun Vars
      40.     private bool isFiring = false;          // is the machine gun firing?  used for decreasing accuracy while sustaining fire
      41.  
      42.     //Shotgun Specific Vars
      43.     public int pelletsPerShot = 10;         // number of pellets per round fired for the shotgun
      44.  
      45.     //Burst Specific Vars
      46.     public int roundsPerBurst = 3;          // number of rounds per burst fire
      47.     public float lagBetweenShots = 0.5f;    // time between each shot in a burst
      48.  
      49.     //Launcher Specific Vars  
      50.  
      51.     // basic stats
      52.     public int range = 300;                 // range for raycast bullets... bulletType = Ray
      53.     public float damage = 20.0f;            // bullet damage
      54.     public float maxPenetration = 3.0f;     // how many impacts the bullet can survive
      55.     public float fireRate = 0.5f;           // how fast the gun shoots... time between shots can be fired
      56.     public int impactForce = 50;            // how much force applied to a rigid body
      57.     public float bulletSpeed = 200.0f;      // how fast are your bullets
      58.  
      59.     public int bulletsPerClip = 50;         // number of bullets in each clip
      60.     public int numberOfClips = 5;           // number of clips you start with
      61.     public int maxNumberOfClips = 10;       // maximum number of clips you can hold
      62.     private int bulletsLeft;                // bullets in the gun-- current clip
      63.        
      64.     public float baseSpread = 1.0f;         // how accurate the weapon starts out... smaller the number the more accurate
      65.     public float maxSpread = 4.0f;          // maximum inaccuracy for the weapon
      66.     public float spreadPerSecond = 0.2f;    // if trigger held down, increase the spread of bullets
      67.     public float spread = 0.0f;             // current spread of the gun
      68.     public float decreaseSpreadPerSec = 0.5f;// amount of accuracy regained per frame when the gun isn't being fired
      69.    
      70.     public float reloadTime = 1.0f;         // time it takes to reload the weapon
      71.     private bool isReloading = false;       // am I in the process of reloading
      72.     // used for tracer rendering
      73.     public int shotsFired = 0;              // shots fired since last tracer round
      74.     public int roundsPerTracer = 1;         // number of rounds per tracer
      75.  
      76.     private int m_LastFrameShot = -1;       // last frame a shot was fired
      77.     private float nextFireTime = 0.0f;      // able to fire again on this frame
      78.  
      79.     private float[] bulletInfo = new float[6];// all of the info sent to a fired bullet
      80.  
      81.     //Network Parts ...yeah
      82.     bool localPlayer = true; //set to false // Am I a local player... or networked
      83.     string localPlayerName = "";            // what's my name
      84.     //Transform myTrans;                    // my transform
      85.  
      86.  
      87.     // Setting up variables as soon as a level starts
      88.     void Start()
      89.     {
      90.         animator = GetComponent<Animator>();
      91.         //myTrans = transform;
      92.         bulletsLeft = bulletsPerClip; // load gun on startup
      93.         //localPlayerName = PlayerPrefs.GetString("playerName");  // get the name of the player
      94.     }
      95.     // check whats the player is doing every frame
      96.     bool Update()
      97.     {
      98.         if (!localPlayer)
      99.         {
      100.             return false;  // if not the local player.... exit function
      101.         }
      102.      
      103.         // Did the user press fire.... and what kind of weapon are they using ?  ===============
      104.         switch (typeOfGun)
      105.         {
      106.             case weaponType.Shotgun:
      107.                 if (Input.GetButtonDown("Fire1"))
      108.                 {
      109.                     //Debug.Log("Shotgun Fire Called");
      110.                     ShotGun_Fire();  // fire shotgun
      111.                 }
      112.                 break;
      113.             case weaponType.Machinegun:
      114.                 if (Input.GetButton("Fire1"))
      115.                 {                  
      116.                     MachineGun_Fire();   // fire machine gun                
      117.                 }
      118.                 break;
      119.             case weaponType.Burst:
      120.                 if (Input.GetButtonDown("Fire1"))
      121.                 {
      122.                    StartCoroutine("Burst_Fire"); // fire off a burst of rounds                  
      123.                 }
      124.                 break;
      125.  
      126.             case weaponType.Launcher:
      127.                 if (Input.GetButtonDown("Fire1"))
      128.                 {
      129.                     Launcher_Fire();
      130.                 }
      131.                 break;
      132.         }//=========================================================================================
      133.  
      134.         if (Input.GetButton("Fire2"))
      135.         {
      136.             if (weaponCamera)
      137.             {
      138.                 weaponCamera.GetComponent<Camera>().enabled = true;
      139.                 mainCamera.GetComponent<Camera>().enabled = false;
      140.             }
      141.         }
      142.         else
      143.         {
      144.             weaponCamera.GetComponent<Camera>().enabled = false;
      145.             mainCamera.GetComponent<Camera>().enabled = true;
      146.         }
      147.  
      148.         //used to decrease weapon accuracy as long as the trigger remains down =====================
      149.         if (Input.GetButtonDown("Fire1"))
      150.         {
      151.             isFiring = true; // fire is down, gun is firing
      152.         }
      153.         if (Input.GetButtonUp("Fire1"))
      154.         {
      155.             isFiring = false; // if fire is up... gun is not firing
      156.         }
      157.         if (isFiring) // if the gun is firing
      158.         {
      159.             spread += spreadPerSecond; // gun is less accurate with the trigger held down
      160.         }
      161.         else
      162.         {
      163.             spread -= decreaseSpreadPerSec; // gun regains accuracy when trigger is released
      164.         }
      165.         //===========================================================================================
      166.         return true;
      167.     }
      168.     // update weapon flashes after checking user inout in update function
      169.     void LateUpdate()
      170.     {
      171.         if (muzzleFlash || lightFlash)  // need to have a muzzle or light flash in order to enable or disable them
      172.         {
      173.             // We shot this frame, enable the muzzle flash
      174.             if (m_LastFrameShot == Time.frameCount)
      175.             {
      176.                 muzzleFlash.transform.localRotation = Quaternion.AngleAxis(Random.value * 57.3f, Vector3.forward);
      177.                 muzzleFlash.enabled = true;// enable the muzzle and light flashes
      178.                 lightFlash.enabled = true;
      179.             }
      180.             else
      181.             {
      182.                 muzzleFlash.enabled = false; // disable the light and muzzle flashes
      183.                 lightFlash.enabled = false;
      184.             }
      185.         }
      186.  
      187.         if (spread >= maxSpread)
      188.         {
      189.             spread = maxSpread;  //if current spread is greater then max... set to max
      190.         }
      191.         else
      192.         {
      193.             if (spread <= baseSpread)
      194.             {
      195.                 spread = baseSpread; //if current spread is less then base, set to base
      196.             }
      197.         }
      198.     }
      199.     // fire the machine gun
      200.     void MachineGun_Fire()
      201.     {
      202.         if (bulletsLeft <= 0)
      203.         {
      204.                     StartCoroutine("reload");
      205.             return;
      206.         }
      207.         // If there is more than one bullet between the last and this frame
      208.         // Reset the nextFireTime
      209.         if (Time.time - fireRate > nextFireTime)
      210.             nextFireTime = Time.time - Time.deltaTime;
      211.  
      212.         // Keep firing until we used up the fire time
      213.         while (nextFireTime < Time.time)
      214.         {
      215.             switch (typeOfBullet)
      216.             {
      217.                 case BulletType.Physical:
      218.                     StartCoroutine("FireOneShot");  // fire a physical bullet
      219.                     break;
      220.                 case BulletType.Raycast:
      221.                     StartCoroutine("FireOneRay");  // fire a raycast.... change to FireOneRay
      222.                     break;
      223.                 default:
      224.                     Debug.Log("error in bullet type");
      225.                     break;
      226.             }
      227.             shotsFired++;
      228.             bulletsLeft--;
      229.             nextFireTime += fireRate;
      230.             EjectShell();
      231.         }
      232.        
      233.     }
      234.     // fire the burst rifle
      235.     IEnumerator Burst_Fire()
      236.     {
      237.         int shotCounter = 0;
      238.  
      239.         if (bulletsLeft <= 0)
      240.         {
      241.             StartCoroutine("reload");
      242.             yield break;//return;
      243.         }
      244.  
      245.         // If there is more than one bullet between the last and this frame
      246.         // Reset the nextFireTime
      247.         if (Time.time - fireRate > nextFireTime)
      248.             nextFireTime = Time.time - Time.deltaTime;
      249.  
      250.         // Keep firing until we used up the fire time
      251.         while (nextFireTime < Time.time)
      252.         {
      253.             while (shotCounter < roundsPerBurst)
      254.             {
      255.                 //Debug.Log(" shotCounter = " + shotCounter + ", roundsPerBurst = "+roundsPerBurst);
      256.                 switch (typeOfBullet)
      257.                 {
      258.                     case BulletType.Physical:
      259.                         StartCoroutine("FireOneShot");  // fire a physical bullet
      260.                         break;
      261.                     case BulletType.Raycast:
      262.                         StartCoroutine("FireOneRay");  // fire a raycast.... change to FireOneRay
      263.                         break;
      264.                     default:
      265.                         Debug.Log("error in bullet type");
      266.                         break;
      267.                 }              
      268.                 //Debug.Log("FireOneShot Called in Fire function.");
      269.                 shotCounter++;
      270.                 shotsFired++;
      271.                 bulletsLeft--; // subtract a bullet
      272.                 EjectShell();
      273.                 yield return new WaitForSeconds(lagBetweenShots);              
      274.             }
      275.  
      276.             nextFireTime += fireRate;
      277.         }
      278.     }
      279.     // fire the shotgun
      280.     void ShotGun_Fire()
      281.     {
      282.         int pelletCounter = 0;  // counter used for pellets per round
      283.  
      284.         if (bulletsLeft == 0)
      285.         {
      286.             StartCoroutine("reload"); // if out of ammo, reload
      287.             return;
      288.         }
      289.  
      290.         // If there is more than one bullet between the last and this frame
      291.         // Reset the nextFireTime
      292.         if (Time.time - fireRate > nextFireTime)
      293.             nextFireTime = Time.time - Time.deltaTime;
      294.  
      295.         // Keep firing until we used up the fire time
      296.         while (nextFireTime < Time.time)
      297.         {
      298.             do
      299.             {
      300.                 switch (typeOfBullet)
      301.                 {
      302.                     case BulletType.Physical:
      303.                         StartCoroutine("FireOneShot");  // fire a physical bullet
      304.                         break;
      305.                     case BulletType.Raycast:
      306.                         StartCoroutine("FireOneRay");  // fire a raycast.... change to FireOneRay
      307.                         break;
      308.                     default:
      309.                         Debug.Log("error in bullet type");
      310.                         break;
      311.                 }
      312.                 pelletCounter++; // add another pellet
      313.                 shotsFired++; // another shot was fired              
      314.             } while (pelletCounter < pelletsPerShot); // if number of pellets fired is less then pellets per round... fire more pellets
      315.             EjectShell(); // eject 1 shell
      316.             nextFireTime += fireRate;  // can fire another shot in "firerate" number of frames
      317.             bulletsLeft--; // subtract a bullet
      318.         }
      319.     }
      320.     // fire your launcher
      321.     void Launcher_Fire()
      322.     {
      323.         if (bulletsLeft == 0)
      324.         {
      325.             StartCoroutine("reload"); // if out of ammo, reload
      326.             return;
      327.         }
      328.  
      329.         // If there is more than one bullet between the last and this frame
      330.         // Reset the nextFireTime
      331.         if (Time.time - fireRate > nextFireTime)
      332.             nextFireTime = Time.time - Time.deltaTime;
      333.  
      334.         // Keep firing until we used up the fire time
      335.         while (nextFireTime < Time.time)
      336.         {
      337.             StartCoroutine("FireOneProjectile"); // fire 1 round              
      338.             nextFireTime += fireRate;  // can fire another shot in "firerate" number of frames
      339.             bulletsLeft--; // subtract a bullet
      340.         }
      341.     }
      342.     // Create and fire a bullet
      343.     IEnumerator FireOneShot()
      344.     {
      345.         Vector3 position = muzzlePoint.position; // position to spawn bullet is at the muzzle point of the gun      
      346.  
      347.         // set the gun's info into an array to send to the bullet
      348.         bulletInfo[0] = damage;
      349.         bulletInfo[1] = impactForce;
      350.         bulletInfo[2] = maxPenetration;
      351.         bulletInfo[3] = maxSpread;
      352.         bulletInfo[4] = spread;
      353.         bulletInfo[5] = bulletSpeed;
      354.  
      355.         //bullet info is set up in start function
      356.         GameObject newBullet = Instantiate(bullet, position, transform.parent.rotation) as GameObject; // create a bullet
      357.         newBullet.SendMessageUpwards("SetUp", bulletInfo); // send the gun's info to the bullet
      358.         newBullet.GetComponent<Bullet>().Owner = gunOwner; // owner of the bullet is this gun's owner object
      359.  
      360.         if (!(typeOfGun == weaponType.Launcher))
      361.         {
      362.             if (shotsFired >= roundsPerTracer) // tracer round every so many rounds fired... is there a tracer this round fired?
      363.             {
      364.                 newBullet.GetComponent<Renderer>().enabled = true; // turn on tracer effect
      365.                 shotsFired = 0;                    // reset tracer counter
      366.             }
      367.             else
      368.             {
      369.                 newBullet.GetComponent<Renderer>().enabled = false; // turn off tracer effect
      370.             }
      371.  
      372.             if (GetComponent<AudioSource>())
      373.             {
      374.                 GetComponent<AudioSource>().Play();  // if there is a gun shot sound....play it
      375.             }
      376.         }      
      377.  
      378.         if ((bulletsLeft == 0))
      379.         {
      380.             StartCoroutine("reload");  // if out of bullets.... reload
      381.             yield break;
      382.         }
      383.        
      384.         // Register that we shot this frame,
      385.         // so that the LateUpdate function enabled the muzzleflash renderer for one frame
      386.         m_LastFrameShot = Time.frameCount;
      387.     }
      388.     // Create and Fire a raycast
      389.     IEnumerator FireOneRay()
      390.     {
      391.  
      392.         string[] Info = new string[2];
      393.         int hitCount = 0;
      394.         bool tracerWasFired = false;
      395.         Vector3 position = muzzlePoint.position; // position to spawn bullet is at the muzzle point of the gun
      396.         Vector3 direction = muzzlePoint.TransformDirection(Random.Range(-maxSpread, maxSpread) * spread, Random.Range(-maxSpread, maxSpread) * spread, 1);
      397.         Vector3 dir = (weaponTarget.transform.position - position) + direction;
      398.  
      399.         // set the gun's info into an array to send to the bullet
      400.         bulletInfo[0] = damage;
      401.         bulletInfo[1] = impactForce;
      402.         bulletInfo[2] = maxPenetration;
      403.         bulletInfo[3] = maxSpread;
      404.         bulletInfo[4] = spread;
      405.         bulletInfo[5] = bulletSpeed;
      406.  
      407.         if (shotsFired >= roundsPerTracer)
      408.         {
      409.             FireOneTracer(bulletInfo);
      410.             shotsFired = 0;
      411.             tracerWasFired = true;
      412.         }        
      413.        
      414.         RaycastHit[] hits = Physics.RaycastAll(position , dir, range);
      415.  
      416.         for (int i = 0; i < hits.Length; i++)
      417.         {
      418.             if (hitCount >= maxPenetration)
      419.             {
      420.                 yield break;
      421.             }          
      422.  
      423.             RaycastHit hit = hits[i];
      424.             //Debug.Log( "Bullet hit " + hit.collider.gameObject.name + " at " + hit.point.ToString() );
      425.  
      426.             // notify hit
      427.             if (!tracerWasFired)
      428.             { // tracers are set to show impact effects... we dont want to show more then 1 per bullet fired
      429.                 ShowHits(hit); // show impacts effects if no tracer was fired this round
      430.             }
      431.  
      432.             Info[0] = localPlayerName;
      433.             Info[1] = damage.ToString();
      434.             hit.collider.SendMessageUpwards("ImHit", Info, SendMessageOptions.DontRequireReceiver);
      435.             // Debug.Log("if " + hitCount + " > " + maxHits + " then destroy bullet...");  
      436.             hitCount++;
      437.         }      
      438.     }
      439.     // Create and Fire 1 launcher projectile
      440.     IEnumerator FireOneProjectile()
      441.     {
      442.         Vector3 position = muzzlePoint.position; // position to spawn rocket / grenade is at the muzzle point of the gun
      443.  
      444.         bulletInfo[0] = damage;
      445.         bulletInfo[1] = impactForce;
      446.         bulletInfo[2] = maxPenetration;
      447.         bulletInfo[3] = maxSpread;
      448.         bulletInfo[4] = spread;
      449.         bulletInfo[5] = bulletSpeed;
      450.  
      451.         switch (typeOfLauncher)
      452.         {
      453.             case LauncherType.Grenade:
      454.                 GameObject newNoobTube = Instantiate(grenade, position, transform.parent.rotation) as GameObject;
      455.                 newNoobTube.SendMessageUpwards("SetUp", bulletInfo);
      456.                 break;
      457.             case LauncherType.Rocket:
      458.                 GameObject newRocket = Instantiate(rocket, position, transform.parent.rotation) as GameObject;
      459.                 newRocket.SendMessageUpwards("SetUp", bulletInfo);
      460.                 break;
      461.             default:
      462.                 Debug.Log("invalid launcher type.... default fired");
      463.                 break;
      464.         }
      465.  
      466.         if (GetComponent<AudioSource>())
      467.         {
      468.             GetComponent<AudioSource>().Play();  // if there is a gun shot sound....play it
      469.         }
      470.  
      471.         if ((bulletsLeft == 0))
      472.         {
      473.             StartCoroutine("reload");  // if out of bullets.... reload
      474.             yield break;
      475.         }
      476.  
      477.         // Register that we shot this frame,
      478.         // so that the LateUpdate function enabled the muzzleflash renderer for one frame
      479.         m_LastFrameShot = Time.frameCount;
      480.  
      481.     }
      482.     // create and "fire" an empty shell
      483.     void EjectShell()
      484.     {
      485.         Vector3 position = ejectPoint.position; // ejectile spawn point at gun's ejection point
      486.        
      487.         if (shell)
      488.         {
      489.             Rigidbody newShell = Instantiate(shell, position, transform.parent.rotation) as Rigidbody; // create empty shell
      490.             //give ejectile a slightly random ejection velocity and direction
      491.             newShell.velocity = transform.TransformDirection(Random.Range(-2, 2) - 3.0f, Random.Range(-1, 2) + 3.0f, -Random.Range(-2, 2) + 1.0f);
      492.         }
      493.     }
      494.     // tracer rounds for raycast bullets
      495.     void FireOneTracer(float[] info)
      496.     {
      497.         Vector3 position = muzzlePoint.position;
      498.         GameObject newTracer = Instantiate(bullet, position, transform.parent.rotation) as GameObject; // create a bullet
      499.         newTracer.SendMessageUpwards("SetUp", info); // send the gun's info to the bullet
      500.         newTracer.SendMessageUpwards("SetTracer");  // tell the bullet it is only a tracer
      501.     }
      502.     //effects for raycast bullets
      503.     void ShowHits(RaycastHit hit)
      504.     {
      505.         switch (hit.transform.tag)
      506.         {
      507.             case "bullet":
      508.                 // do nothing if 2 bullets collide
      509.                 break;
      510.             case "Player":
      511.                 // add blood effect
      512.                 break;
      513.             case "wood":
      514.                 // add wood impact effects
      515.                 break;
      516.             case "stone":
      517.                 // add stone impact effect
      518.                 break;
      519.             case "ground":
      520.                 // add dirt or ground  impact effect
      521.                 break;
      522.             default: // default impact effect and bullet hole
      523.                 Instantiate(impactEffect, hit.point + 0.1f * hit.normal, Quaternion.FromToRotation(Vector3.up, hit.normal));
      524.                 GameObject newBulletHole = Instantiate(bulletHole, hit.point, Quaternion.FromToRotation(Vector3.up, hit.normal)) as GameObject;
      525.                 newBulletHole.transform.parent = hit.transform;
      526.                 break;
      527.         }
      528.     }
      529.     // reload your weapon
      530.     IEnumerator reload()
      531.     {
      532.         if (isReloading)
      533.         {
      534.             yield break; // if already reloading... exit and wait till reload is finished
      535.         }
      536.  
      537.         {
      538.             {
      539.             isReloading = true; // we are now reloading
      540.             numberOfClips--; // take away a clip
      541.             yield return new WaitForSeconds(reloadTime); // wait for set reload time
      542.             bulletsLeft = bulletsPerClip; // fill up the gun
      543.             }
      544.         }
      545.  
      546.         isReloading = false; // done reloading
      547.     }
      548. }
    It's a script i got from Nova i believe his name was.
    So my problem here is, the gun auto reloads, i want to make it only reload when i press "R".
    I tried adding if(Input.GetKeyDown("r")) Both in the IEunmerator reload AND Machine gun fire under the Bulletsleft >= 0; Either, it just doesn't reload, or gives me unlimited ammo for some reason :/
    I really don't know what to do :| Maybe it's an obvious/easy solution, but i don't know. I barely know anything about scripting. I know a little of the basics but yeah, other than that, nope :/

    Any help would be appreciated :D

    BTW I'm really sorry about the long script, but it's easier if you have a whole view of the script i suppose :)
     
    Last edited: Aug 5, 2015
  2. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    [code ][/code ] tags.... there is a sticky at the top of the scripting section on them.
     
  3. hattyh

    hattyh

    Joined:
    Jul 8, 2015
    Posts:
    15
    Oops, sry got it now :)
     
  4. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,384
    Use something like
    Code (csharp):
    1. while (Input.GetKeyDown(KeyCode.R)
    2. {
    3.    // do reload stuff
    4. }
    5.  
    If the key isn't down then it won't continue the Coroutine.
     
  5. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    I think part of the problem is even though this code has good comments it's way too complicated for a beginner, I'm a sort-of beginner now and struggling to read it all clearly.



    Found this after glancing around youtube, you may find better ones out there, but what they do is give you very basic scripts to work from and you'll know what everything does then add on from there. Or move onto more complicated scripts.

    Keep things simple and work your way up, if you can't do that, then get somebody else to do the programming for you.
     
  6. SomeGuy22

    SomeGuy22

    Joined:
    Jun 3, 2011
    Posts:
    722
    What you tried with GetKeyDown should be correct. But you should be using KeyCode.R instead of "r". GetButtonDown("String") is for Buttons set up in the Input menu. You'd want to do
    Code (CSharp):
    1.  if (bulletsLeft <= 0 && Input.GetKeyDown(KeyCode.R))
    And do listen to Lethn's advice and do some tutorials before tackling complex scripts you can't understand :)
     
  7. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Currently looking at camera scripting and getting a headache -_- :D
     
  8. SomeGuy22

    SomeGuy22

    Joined:
    Jun 3, 2011
    Posts:
    722
    I've done camera scripting before haha is there anything you don't understand?
     
  9. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    I posted a thread up that's gone to the second page now if you'd be kind enough to look, it shouldn't be a difficult problem, it involved getting a camera position I think, hope this doesn't count as hijacking a thread.
     
  10. hattyh

    hattyh

    Joined:
    Jul 8, 2015
    Posts:
    15
    It got unlimited ammo again, it reloads constantly :/
    And i didn't even press R, this is so weird :|
     
  11. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    Like I said, I'd start afresh if you're having tons of problems, go from the tutorial I posted and see how that works out for you.
     
  12. hattyh

    hattyh

    Joined:
    Jul 8, 2015
    Posts:
    15
    Yeah, but all i need is for it too not reload automatically, and only when i press "R", but if this isn't gonna work anytime soon, i'll do that tutorial. Because so far this is a pain in the arse man.
     
  13. Lethn

    Lethn

    Joined:
    May 18, 2015
    Posts:
    1,583
    It's a very complicated script, as for reloading, it shouldn't be anything more than a couple of variables at most which is why you're having such a hard time, because you're having to dig through all that code to find one little function, I know the feeling.
     
  14. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    The script is complex not because it's advanced, but because it is trying to do a lot of things. It's a dozen different weapons, and each of them behaves differently. It should really be several scripts.

    Structure aside, the easiest way to do this would just be to put each call to StartCoroutine(Reload()); inside an if statement. Like this.

    Code (CSharp):
    1. if (Input.GetKeyDown(KeyCode.R)){
    2.     StartCoroutine(Reload());
    3. }
     
  15. hattyh

    hattyh

    Joined:
    Jul 8, 2015
    Posts:
    15
    Still reloads constantly :/ I really don't get it, what kind of sorcery is this?
     
  16. hattyh

    hattyh

    Joined:
    Jul 8, 2015
    Posts:
    15
    Somebody please have an answer for this i'm friggin dying here, i can't figure this out...
    When i have it like this
    if(bulletsLeft <=0), its fine(except it auto reloads), but as soon as i change it too
    if(bulletsLeft <=0 && Input.GetKeyDown(KeyCode.R))
    Then it calls the reload function, but ignores the yield returnnew WaitForSeconds thing...AND I DIDN'T EVEN PRESS "R":|
    So it insta reloads, aka unlimited ammo nonstop shooting.

    It's so annoying...