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
1
Question by HungoverCabbage · Apr 06, 2012 at 09:34 PM · c#coroutinewaitforseconds

Having trouble figuring out coroutines in C#

I'm trying to make an enemy encounter in my game where the enemy will move from left to right and shoots projectiles in 1 second intervals. I've got the movements working fine but I can't get the projectiles to spawn every second. I've checked around and using a coroutine seems to be the way to go about but I can't for the life of me figure out how to use them properly.

The way I have my script set up at the moment, it's spewing out projectiles every frame because I'm calling the coroutine inside Update() but I'm not entirely sure where else I could put it if I want the script to constantly fire until the gameObject is destroyed.

 GameObject proj;
 IEnumerator timerSpawn()
 {
    yield return new WaitForSeconds(1);
         
    /**Create a temp projectile*/
    GameObject projectile;
    //Instantiate the bullet at the position and rotation of the player
    projectile = Instantiate(proj,transform.position,transform.rotation) as GameObject;        
 }

and then in my Update()

 void Update () 
 {
    StartCoroutine(timerSpawn());
    ...
    ...
 }

I'm fairly new to C# and Unity in general so if anyone could help me out on how to go about implementing this, I'd greatly appreciate it.

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
3
Best Answer

Answer by rutter · Apr 06, 2012 at 09:51 PM

If I understand things right, you probably just want to start a looping coroutine from Start() or Awake(). Something like this:

 bool keepSpawning = true;
 
 void Start()
 {
     StartCoroutine(TimerSpawn());
 }
 
 IEnumerator TimerSpawn()
 {
     while (keepSpawning)
     {
         Debug.Log("Spawn something");
         yield return new WaitForSeconds(1f);
     }
 }

A coroutine will only fire once per call to StartCoroutine(), but as you can see from the example it's possible to keep the function going with a loop. The function will pause on every yield, and will continue execution after the yield.

You can probably figure out where to take it from there.

Don't forget that you can always check the official script reference:

  • `StartCoroutine()`

  • Overview: Coroutines and yield

If this is too confusing, remember that you can also use `Invoke()` or `InvokeRepeating()`.

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 HungoverCabbage · Apr 06, 2012 at 10:06 PM 0
Share

Cheers this worked perfectly.

avatar image
0

Answer by aldonaletto · Apr 06, 2012 at 09:43 PM

You should use a boolean flag to stop firing coroutines while the last one has not finished:

bool firing = false; // flag "I'm shooting alredy!"

void Update() { // only start a new coroutine when the previous one has finished: if (!firing) StartCoroutine(timerSpawn()); ... }

GameObject proj; IEnumerator timerSpawn() { firing = true; // the coroutine is running! yield return new WaitForSeconds(1); /**Create a temp projectile*/ GameObject projectile; //Instantiate the bullet at the position and rotation of the player projectile = Instantiate(proj,transform.position,transform.rotation) as GameObject; firing = false; // coroutine ended } Additionally, you must give velocity to the projectile, or it will not move. Another issue: if created at player position, it will collide with the player. You should usually have an empty game object (childed to the player) at the desired spawn point, and pass this position to Instantiate.

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 HungoverCabbage · Apr 06, 2012 at 10:13 PM 0
Share

Thanks for the answer but I actually tried this myself at first and I think because its being called in Update() it still gives the same problem and is called every frame regardless.

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

6 People are following this question.

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

Related Questions

Rotate an object using Quaternion.RotateTowards() inside a Coroutine? 1 Answer

C# simple delay execution without coroutine? 2 Answers

How to get precise spawn interval (C#)? 3 Answers

WaitForSeconds not working C# 1 Answer

I'm having trouble with Coroutines.. 2 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