• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by BrettRiet · Feb 07, 2011 at 12:43 AM · javascriptreloadmachinegun

Reload when press "r"?

Basicly it kind of works but it reloads when you empty a clip.... or if are in the process of shooting (im holding down the mouse button) and i press "r" it will reload but if i just push "r" (even with only half a magazine or something) it wont reload. i have tried moving the "if(Input.GetKeyDown("r")) Reload();" to different places but it doesnt help. i've also tried making new functions. how come this happens?

var range = 100.0; var fireRate = 0.05; var force = 10.0; var damage = 5.0; var bulletsPerClip = 40; var clips = 20; var reloadTime = 0.5; var reloadSound : AudioClip;

 private var hitParticles : ParticleEmitter;
 var muzzleFlash : Renderer;

 private var clipsLeft : int = 0;
 private var bulletsLeft : int = 0;
 private var nextFireTime = 0.0;
 private var m_LastFrameShot = -1;


 function Start () {
     hitParticles = GetComponentInChildren(ParticleEmitter);

     // We don't want to emit particles all the time, only when we hit something.
     if (hitParticles)
         hitParticles.emit = false;
     bulletsLeft = bulletsPerClip;
     clipsLeft = clips;

 }



 function LateUpdate() {

     if (muzzleFlash) {
         // We shot this frame, enable the muzzle flash
         if (m_LastFrameShot == Time.frameCount) {
             muzzleFlash.transform.localRotation = Quaternion.AngleAxis(Random.value * 360, Vector3.forward);
             muzzleFlash.enabled = true;

             if (audio) {
                 if (!audio.isPlaying)
                     audio.Play();
                 audio.loop = true;
             }
         } else {
         // We didn't, disable the muzzle flash
             muzzleFlash.enabled = false;
             enabled = false;


             // Play sound
             if (audio)
             {
                 audio.loop = false;
             }
         }
     }
 }



 function Fire () {




     if (bulletsLeft == 0)
         return;

     // If there is more than one bullet between the last and this frame
     // Reset the nextFireTime
     if (Time.time - fireRate > nextFireTime)
         nextFireTime = Time.time - Time.deltaTime;

     // Keep firing until we used up the fire time
     while( nextFireTime < Time.time && bulletsLeft != 0) {
         FireOneShot();
         nextFireTime += fireRate;





     }
 }

 function FireOneShot () {




     var direction = transform.TransformDirection(Vector3.forward);
     var hit : RaycastHit;




     // Did we hit anything?
     if (Physics.Raycast (transform.position, direction, hit, range)) {
         // Apply a force to the rigidbody we hit
         if (hit.rigidbody)
             hit.rigidbody.AddForceAtPosition(force * direction, hit.point);

         // Place the particle system for spawing out of place where we hit the surface!
         // And spawn a couple of particles
         if (hitParticles) {
             hitParticles.transform.position = hit.point;
             hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
             hitParticles.Emit();
         }

         // Send a damage message to the hit object          
         hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
     }

     bulletsLeft--;

     // Register that we shot this frame,
     // so that the LateUpdate function enabled the muzzleflash renderer for one frame
     m_LastFrameShot = Time.frameCount;
     enabled = true;

     // Reload gun in reload Time        


     if (bulletsLeft == 0)
     Reload();

     if(Input.GetKeyDown("r"))
     Reload();


     }




 function Reload () 
 {



 audio.PlayOneShot(reloadSound, 1.0 / audio.volume);

 animation.CrossFade ("Reload right");

     // Wait for reload time first - then add more bullets!




     yield WaitForSeconds(reloadTime);



     if (clipsLeft > 0) {
         clipsLeft--;
         bulletsLeft = bulletsPerClip;



     }
     }







 function GetBulletsLeft () {
     return bulletsLeft;
 }

 function GetClipsLeft (){
     return clipsLeft;
     }








UPDATE*** New Script(SLIGHTLy) modified added new function for Input.GetKeyDown.....

var range = 100.0; var fireRate = 0.05; var force = 10.0; var damage = 5.0; var bulletsPerClip = 40; var clips = 20; var reloadTime = 0.5; var reloadSound : AudioClip;

private var hitParticles : ParticleEmitter; var muzzleFlash : Renderer;

private var clipsLeft : int = 0; private var bulletsLeft : int = 0; private var nextFireTime = 0.0; private var m_LastFrameShot = -1;

function Update(){

if (Input.GetKeyDown("r")) Reload(); }

function Start () { hitParticles = GetComponentInChildren(ParticleEmitter);

 // We don't want to emit particles all the time, only when we hit something.
 if (hitParticles)
     hitParticles.emit = false;
 bulletsLeft = bulletsPerClip;
 clipsLeft = clips;

}

function LateUpdate() {

 if (muzzleFlash) {
     // We shot this frame, enable the muzzle flash
     if (m_LastFrameShot == Time.frameCount) {
         muzzleFlash.transform.localRotation = Quaternion.AngleAxis(Random.value * 360, Vector3.forward);
         muzzleFlash.enabled = true;

         if (audio) {
             if (!audio.isPlaying)
                 audio.Play();
             audio.loop = true;
         }
     } else {
     // We didn't, disable the muzzle flash
         muzzleFlash.enabled = false;
         enabled = false;


         // Play sound
         if (audio)
         {
             audio.loop = false;
         }
     }
 }

}

function Fire () {

 if (bulletsLeft == 0)
     return;

 // If there is more than one bullet between the last and this frame
 // Reset the nextFireTime
 if (Time.time - fireRate > nextFireTime)
     nextFireTime = Time.time - Time.deltaTime;

 // Keep firing until we used up the fire time
 while( nextFireTime < Time.time && bulletsLeft != 0) {
     FireOneShot();
     nextFireTime += fireRate;





 }

}

function FireOneShot () {

 var direction = transform.TransformDirection(Vector3.forward);
 var hit : RaycastHit;




 // Did we hit anything?
 if (Physics.Raycast (transform.position, direction, hit, range)) {
     // Apply a force to the rigidbody we hit
     if (hit.rigidbody)
         hit.rigidbody.AddForceAtPosition(force * direction, hit.point);

     // Place the particle system for spawing out of place where we hit the surface!
     // And spawn a couple of particles
     if (hitParticles) {
         hitParticles.transform.position = hit.point;
         hitParticles.transform.rotation = Quaternion.FromToRotation(Vector3.up, hit.normal);
         hitParticles.Emit();
     }

     // Send a damage message to the hit object          
     hit.collider.SendMessageUpwards("ApplyDamage", damage, SendMessageOptions.DontRequireReceiver);
 }

 bulletsLeft--;

 // Register that we shot this frame,
 // so that the LateUpdate function enabled the muzzleflash renderer for one frame
 m_LastFrameShot = Time.frameCount;
 enabled = true;

 // Reload gun in reload Time        


 if (bulletsLeft == 0)
 Reload();

 }




function Reload () {

audio.PlayOneShot(reloadSound, 1.0 / audio.volume);

animation.CrossFade ("Reload right");

 // Wait for reload time first - then add more bullets!




 yield WaitForSeconds(reloadTime);



 if (clipsLeft > 0) {
     clipsLeft--;
     bulletsLeft = bulletsPerClip;



 }
 }







function GetBulletsLeft () { return bulletsLeft; }

function GetClipsLeft (){ return clipsLeft; }

Comment

People who like this

0 Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Uriel_96 · Feb 07, 2011 at 01:02 AM 0
Share

have you try putting in Update function??

avatar image BrettRiet · Feb 07, 2011 at 01:03 AM 0
Share

i have it doesn't work anywhere or way??

1 Reply

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by Molix · Feb 07, 2011 at 02:03 AM

It appears that the only place Reload() is called is from within FireOneShot(), so if you are not firing it is impossible to even get to the reload code. Move the check for the 'r' key to Update().

Comment
Senhor de todo o Mal
BrettRiet
Kashaunzilla

People who like this

3 Show 6 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image BrettRiet · Feb 08, 2011 at 01:21 AM 0
Share

sorry i;m not very good at scripting... do you mean put "if(Input.GetKeyDown("r")) Reload();" to "function LateUpdate(){" or do i make a new "function"?

avatar image Molix · Feb 08, 2011 at 04:12 AM 0
Share

Yes, those two lines, but put them in Update(), rather than LateUpdate.

avatar image BrettRiet · Feb 08, 2011 at 05:33 AM 0
Share

no matter how i put it,it doesn't work? i tried putting the lines in a new function i created "Update()" but it still has to be shooting while i press are there is no way i can put it in?

avatar image BrettRiet · Feb 08, 2011 at 05:34 AM 0
Share

is there some way i can say like " && shooting = false" or something along those lines...

avatar image Molix · Feb 08, 2011 at 04:16 PM 0
Share

You should probably put up your new code.

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

No one has followed this question yet.

Related Questions

Help in change the rate of fire. 1 Answer

Prevent countdown from reloading every time a new scene is loaded 1 Answer

Make the animation play at the start of the time waited, not the end of it? 1 Answer

Setting Scroll View Width GUILayout 1 Answer

Realistic reloading system 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges