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
4
Question by Jammer3000 · Jul 12, 2012 at 04:27 PM · gameobjectdelayshot

How to delay a shot.

Hi I need to know how to delay a shot. For example I have a game where my player has a gun and I want it so when he holds down the left mouse button the shots fire automatically, with a delay so its not shooting a hundred bullets a second. Heres the code that makes the gun shoot. This code is in java, and if you can please make a public variable so I can change the delay time. The name of the gameobject is laser which you will probably notice in the code. This code does work, but it just needs a delay, and if your wondering I don't want the if statement to go from Input.GetButton to Input.GetButtonUp or Down. I know that that will make it so the player just has to click it and it will fire, but thats not what I want it to do. I want it the same, but just a delay on when the bullets fire when I hold down the left mouse button. Thanks so much.

var throwSound : AudioClip; var coconutObject : Rigidbody; var throwForce : float;

function Update () {

if(Input.GetButton("Fire1")){ audio.PlayOneShot(throwSound); var newCoconut : Rigidbody = Instantiate(coconutObject, transform.position, transform.rotation); newCoconut.rigidbody.velocity = transform.TransformDirection(Vector3(0,0, throwForce)); newCoconut.name = "laser"; Physics.IgnoreCollision(transform.root.collider, newCoconut.collider, true);

} }

@script RequireComponent(AudioSource)

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

4 Replies

· Add your reply
  • Sort: 
avatar image
28

Answer by Maddogc · Jul 12, 2012 at 04:51 PM

Here you are, Unity's solution examples in JS and C# to solve your problem:

JS

 // Instantiates a projectile off every 0.5 seconds,
 // if the Fire1 button (default is ctrl) is pressed.

 var projectile : GameObject;
 var fireRate = 0.5;
 private var nextFire = 0.0;

 function Update ()
 {

 if (Input.GetButton ("Fire1") && Time.time > nextFire) 
 {
     nextFire = Time.time + fireRate;
     var clone = Instantiate (projectile, transform.position, transform.rotation);
 }

 }


C#

 using UnityEngine;
 using System.Collections;
 
 public class example : MonoBehaviour 
 {
  public GameObject projectile;
  public float fireRate = 0.5F;
  private float nextFire = 0.0F;
 
  void Update() 
  {
     if (Input.GetButton("Fire1") && Time.time > nextFire) 
     {
         nextFire = Time.time + fireRate;
         GameObject clone = Instantiate(projectile, transform.position, transform.rotation) as GameObject;
     }
  }
 }
Comment
Add comment · Show 4 · 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 Je Hwan Yoo · Jan 26, 2016 at 03:24 AM 0
Share

Thanks for you, I could fix my game :)

avatar image Fornoreason1000 Je Hwan Yoo · Jan 26, 2016 at 03:32 AM 0
Share

If you are satisfied that $$anonymous$$addogc has answered your question please uses the accept button

avatar image mookfasa · Mar 05, 2017 at 04:57 PM 0
Share

Thank you!

avatar image LAKSHAYMAVIA · Sep 13, 2018 at 07:49 AM 0
Share

Thanks this worked.

avatar image
7

Answer by alishka · Jan 26, 2016 at 09:08 AM

Hey! Use a coroutine!

  public void OnClick () {
       if ( canShoot ) {
           StartCoroutine ( shoot() );
       }
 }

  public IEnumerator shoot () {

       //Instantiate your projectile
       shootLogic();
       canShoot = false;

       //wait for some time
       yield return new waitForSeconds (cooldownTime);
       canShoot  = true;

 }

Cheers!

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

Answer by tjbrunetto · Aug 25, 2018 at 04:16 PM

Overall the coroutine is better. The use of the update function on a shot timer produces varying results and inconsistencies. The enumerator works perfectly.

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

Answer by LAKSHAYMAVIA · Sep 13, 2018 at 07:43 AM

I tried with coroutine. but unable to get Desired result.

   void startFire()
     {
       
         if (isFiring)
         {
               Debug.Log("firung");
 
             StartCoroutine(fireCouroutine());
 
             //obj.transform.parent = transform;
         }
     }
 
     IEnumerator fireCouroutine()
     {
         Vector3 offset = new Vector2(1, 0);
         GameObject obj = Instantiate(fire, transform.position + offset, Quaternion.identity);
         obj.GetComponent<SpriteRenderer>().color = Color.yellow;
         obj.GetComponent<Rigidbody2D>().velocity = new Vector2(10, 0);
 
         isFiring = false;
         Debug.Log("1" +isFiring);
         yield return new WaitForSeconds(shootDelay);
        
         isFiring = true;
         Debug.Log("2" + isFiring);
 
     }

I am calling this frunction here.

 if (Input.GetKey(KeyCode.Space) || RightHalf.Contains(touchPos))
         {   
             Debug.Log("fire");
             isFiring = true;
             
              startFire();
            // InvokeRepeating("startFire", 0.003f, 0.4f);
            
             //
         }

Am I doing something wrong.?

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

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

How to delay lines of code. 2 Answers

Using Scripts in AssetBundles 0 Answers

Moveing my camera 1 Answer

Refering to gameobject script is attached to 1 Answer

Where to attach a script? 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