• 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 Althaen · Nov 05, 2012 at 01:47 AM · c#coroutineyieldienumerator

What am I doing wrong with IEnumerator?

I am trying to use IEnumerator to yield between bullet instantiations but it will not yield properly. I got it working perfectly at one point but broke it again later. I think the problem is my misunderstanding of how IEnumerator works.

If anyone knows of a better way for me to achieve my desired function please tell me.

Please have a look over my code and show me what I am doing wrong:

 using UnityEngine;
 using System.Collections;

 public class scarh : MonoBehaviour
 {
     public Rigidbody projectile;
     private bool shooting = false, reloading = false, canShoot = false;
     private int z = 1;
     public int currentAmmo = 20, speed = 500, maxAmmo = 20;
     public float shootDelay = 5.0f;
     
     void Start()
     {
 
     }
     
     void reload()
     {
 //        currentAmmo = maxAmmo;
     }
     
 //    if(currentAmmo <= 0)
 //    {
 //        print ("Reloading!");
 //        reload ();
         //Yield for 3 seconds
 //        yield return new WaitForSeconds(3);
         //Set reload to false so you can shooting again
 //        print ("Reloading complete");
 //        reloading = false;
 //    }
 IEnumerator TimedShooting()
 {
     //While player is shooting
     while(shooting)
     {
         print ("Running IEnumerator");
         //If there is a projectile
         if(projectile)
         {                
             //Instantiate projectile
             Rigidbody newProjectile = Instantiate(projectile, transform.position,
                                                               transform.rotation) as Rigidbody;
                 
             //Give projectile velocity
             newProjectile.velocity = transform.TransformDirection(new Vector3 (0, 0, speed));
                 
             //Remove 1 from currentAmmo
             currentAmmo -= 1;
                 
             //Yield before next shot?
             yield return new WaitForSeconds(shootDelay);
                 print ("Yielding");
         }
     }
 }
     
     void Update ()
     {
         //When holding down Fire1
         if (Input.GetButton("Fire1"))
         {
             shooting = true;
             StartCoroutine ("TimedShooting");
             print ("Shooting: " + shooting);
         }
             
         //When Fire1 is released
         if(Input.GetButtonUp ("Fire1"))
         {
             shooting = false;
             //Set shooting to false
             print ("Shooting: " + shooting);
         }
             
         //Switch fire mode when Z is pressed
         if (Input.GetKeyDown(KeyCode.Z))
         {
             z = (z % 3) + 1;
             print (z);
         }
     }
 }
Comment

People who like this

0 Show 0
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

1 Reply

  • Sort: 
avatar image
Best Answer

Answer by Jessespike · Nov 05, 2012 at 02:25 AM

It's tricky, but the answer is there. Look at these two pieces of code closely:

    //When holding down Fire1
    if (Input.GetButton("Fire1"))
    {
      shooting = true;
      StartCoroutine ("TimedShooting");
      print ("Shooting: " + shooting);
    }


and

 IEnumerator TimedShooting()
 {
     //While player is shooting
     while(shooting)
     {
         print ("Running IEnumerator");
         ...


You're resetting shooting = true and Starting a Coroutine every update/frame. You're basically shooting a bullet every frame now and the yield does nothing helpful. By the time the first shot has finished it's yield, you probably shot like 300 more bullets. So to fix you can do this:

    //When holding down Fire1
    if (Input.GetButton("Fire1"))
    {
     //shooting = true;
     //StartCoroutine ("TimedShooting");
     if (shooting == false) {  // START shooting if not shooting
          shooting = true;
         StartCoroutine ("TimedShooting");
     }


And now you're shootDelay is yielding as intended. But there's still another problem: You can rapid-fire bullets if you spam click. To fix that bug, remove "shooting = false" from GetButtonUp(), and put "shooting = false" to the next line after the shootDelay yield.

Cheers

Comment

People who like this

0 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 Althaen · Nov 05, 2012 at 02:36 AM 0
Share

Thank you so much! It works exactly the way I intended now.

Been trying to figure it out for ages.

Unity Answers is in Read-Only mode

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta on June 13. Please note, Unity Answers is now in read-only so we can prepare for the final data migration.

For more information and updates, please read our full announcement thread in the Unity Forum.

Follow this Question

Answers Answers and Comments

11 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Why Won't My Coroutine Yield? 2 Answers

Waiting twice inside coroutine (C#) 2 Answers

Yield Wait for Seconds (A little help here) 2 Answers

How to have a scene ready loaded for switching? 1 Answer

Create a delay between function executions 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