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 W1k3 · Aug 31, 2013 at 09:28 PM · instantiateyieldloops

Having a strange problem with yield and instantiate (C#)

I'm having a strange problem. I want to make it so if the space bar is pressed, the player shoots a projectile every few seconds. I've tried 2 techniques so far, and the common theme seams to be that if the projectile is set to instantiate every 0 seconds, it explodes like crazy; anything greater, it makes a solid line with some glitchy movements.

Here are some screenshots: http://imgur.com/aRRMThO

If you can think of any way I could space out the projectiles more, or why this is happening it would be very much appreciated.

 using System.Collections;
 
 public class player : MonoBehaviour {
 
     private Transform ship;    
     public int shipspeed = 5;
     public Transform shotPos;
     public float shotForce = 1000f;
     public Rigidbody projectile;
     bool con = true;
     
     void Start () {
     
         
         //spawn position
         ship = transform;
         ship.position = new Vector3(0, -7, 2);
     
     }
     
     void Update () {
  
        //Horizontal movement with arrow keys
        ship.Translate(Vector3.right * shipspeed * Input.GetAxis("Horizontal") * Time.deltaTime);
  
  
     //ship wrapping    
     if(ship.position.x > 6){
            ship.position = new Vector3(-6, -7, 2);
        }
  
     else if(ship.position.x < -6){
  
          ship.position = new Vector3(6, -7, 2);
         }
  
             
         //gun
             
             
             
     if(Input.GetButton("Jump")){
         StartCoroutine("Fire");
     }
     if(Input.GetButtonUp("Jump")){
        StopCoroutine("Jump");
     }
 }
  
 //luanch projectile
 void Shoot (){
        Rigidbody shot = Instantiate(projectile, shotPos.position, shotPos.rotation) as Rigidbody;
             shot.AddForce(shotPos.up * shotForce);
     }    
     
     
 //gun delay loop
     
 IEnumerator Fire(){
            
         while(con == true){
         Shoot ();
             
             yield return new WaitForSeconds(1f);
         }        
     }
 }
Comment
Add comment · Show 1
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 ForgeStudios · Aug 31, 2013 at 10:14 PM 0
Share

Have you tried increasing the wait time? Also, i'm not very experienced w/C#, but I know that it's a fact for javascript that when you use the regular Update() function to run other function that even on a clock, the speed of routines is deter$$anonymous$$ed by the run speed of your project.

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Life Alchemist · Sep 01, 2013 at 04:47 AM

Don't use StartCoroutine and yields in this case. It slows things down when you want things to be instantaneous.

 using UnityEngine;
 using System.Collections;
 
 public class shootGun : MonoBehaviour {
     
     bool shotCooldown;
     private float timer;
     private float cooldown;
     
     // Use this for initialization
     void Start () {
         shotCooldown = false;
         timer = 0.0f;
         cooldown = 1.0f;
     }
     
     // Update is called once per frame
     void Update () {
         if(Input.GetButton("Fire")){ //jump, fire, whatever you want the key to be
             Shoot();
         }
         
         if (shotCooldown == true)
         {
             if (timer < cooldown)
                 timer += Time.deltaTime;
             else
             {
                 shotCooldown = false;
                 timer = 0.0f;
             }
         }
     }
     
     //luanch projectile
     void Shoot (){
         if(shotCooldown == false)
         {
             Rigidbody shot = Instantiate(projectile, shotPos.position, shotPos.rotation) as Rigidbody;
             shot.AddForce(shotPos.up * shotForce);
             
             shotCooldown = true;
         }
     }
 }
 

If you can, try to use less spacing in-between sections of code. Change the cooldown variable to however long you want the interval between shots to be.

Comment
Add comment · Show 3 · 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 Owen-Reynolds · Sep 01, 2013 at 04:06 PM 0
Share

A more standard "Unity" way is to make timer be a real time in seconds, so it stands for "can shoot again when the clock says this." After a shot, set it to Time.time+coolDownSecs;. Before you shoot, check if if(Time.time>=timer).

Avoids the need to hand-add time each frame -- Unity runs the clock for you.

avatar image W1k3 · Sep 01, 2013 at 08:34 PM 0
Share

Thank you so much! It works perfectly.

avatar image Life Alchemist · Sep 02, 2013 at 02:06 AM 0
Share

Ah, what Owen says is good in this case. Since you're calling it and there isn't a need to check anything else except fire key, using Time.time+coolDownSecs is better for "efficient code." Otherwise, they do the same thing if you're not concerned.

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

19 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Yield return inside a loop slowdown problem 2 Answers

How to make a loading feedback for big GameObjects loading? 2 Answers

Why aren't the right amount of blocks instantiating? 0 Answers

Respawn after delay 3 Answers

Instantiating many objects during update lags 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