Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • 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
0
Question by user-3061 (yahoo) · Dec 27, 2010 at 10:28 AM · javascriptfpsgunreload

Some issues with weapon switching and reloading?

Hi, I used the Machinegun.js script from the FPS tutorial :

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; private var hitParticles : ParticleEmitter; var muzzleFlash : Renderer;

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;

}

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 () {

 // Wait for reload time first - then add more bullets!
 yield WaitForSeconds(reloadTime);

 // We have a clip left reload
 if (clips > 0) {
     clips--;
     bulletsLeft = bulletsPerClip;
 }

}

function GetBulletsLeft () { return bulletsLeft;

and the weapon switching script, which is :

function Start () { // Select the first weapon SelectWeapon(0); }

function Update () { // Did the user press fire? if (Input.GetButton ("Fire1")) BroadcastMessage("Fire");

 if (Input.GetKeyDown("1")) {
     SelectWeapon(0);
 }   
 else if (Input.GetKeyDown("2")) {
     SelectWeapon(1);
 }   

}

function SelectWeapon (index : int) { for (var i=0;i<transform.childCount;i++) { // Activate the selected weapon if (i == index) transform.GetChild(i).gameObject.SetActiveRecursively(true); // Deactivate all other weapons else transform.GetChild(i).gameObject.SetActiveRecursively(false); } }

  }

Now, when i switch weapons while reloading (during the time span) and switch back to the machinegun, the machinegun wont reload if there is no bullet available. Can anyone tell me how do i solve this? I tried many ways, like putting an "if the gun is reloading, switch weapons = false" but cant seem to shape it. I also did searched around the forums and found this thread : link

but theres no answer too... can anyone help me with this script? Thanks!

Comment
Add comment
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

2 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by NickCh · Dec 27, 2010 at 11:58 AM

Check the Edit->Project Settings->Input. YOu have to have the keys 1 and 2 enstablished there. just go to the tutorial and see the input from there.

[b]Another logic[/b]

I don't know about FPS tutorial but what i would do is having the two guns at (and at the Hiereancy inside) the FPS prefab.The second gun i would make it invisible and then i would write something like : When User press button 2 make 1st gun invisible and make 2nd gun visible.

That was just a logic that you can base on the script you have from the Tutorial

Comment
Add comment · Show 1 · 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 user-3061 (yahoo) · Dec 27, 2010 at 12:28 PM 0
Share

sorry, you completely misunderstood my question... please read more carefully before answering it, my problem is with the "Reload" and "ChangeWeapons" function.Thanks for the reply tho.

avatar image
0

Answer by KnC_Studios · Jul 30, 2013 at 12:35 AM

Well I had this problem as well and found a guy who fixed. I have since edited the fps tutorial script to fit my needs. You need to set the variable for the reloading object on the gun script. Enjoy!

 var playerWeapons : GameObject;
 var range = 100.0;
 var fireRate = 0.005;
 var force = 5.0;
 var damage = 0.5;
 var bulletsPerClip = 1000;
 var clips = 5;
 var reloadTime = 1;
 private var hitParticles : ParticleEmitter;
 var muzzleFlash : Renderer;
 var reload : AudioClip;
 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;
 }
 
 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 () {
     
         
     playerWeapons.GetComponent(PlayerWeapons).enabled = false;
     // Wait for reload time first - then add more bullets!
     yield WaitForSeconds(reloadTime);
     playerWeapons.GetComponent(PlayerWeapons).enabled = true;
 
     // We have a clip left reload
     if (clips > 0) {
         clips--;
         bulletsLeft = bulletsPerClip;
         audio.PlayOneShot(reload, 1.0 / audio.volume);
 
     }
     
 
 }
 
 function GetBulletsLeft () {
     return bulletsLeft;
 }
Comment
Add comment · 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

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.

Follow this Question

Answers Answers and Comments

1 Person is following this question.

avatar image

Related Questions

Can someone help me fix my Javascript for Flickering Light? 6 Answers

Setting Scroll View Width GUILayout 1 Answer

Need help with bullet/gun scripting 3 Answers

Is there a script out there that actully works for shooting bullets? 2 Answers

Need help... Start Button no longer working!!!!! 0 Answers


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