- Home /
Delay between throwing/firing object
Hi all :D
My first question so go easy on me :P
Im quite new to scripting and I need help with the script , I want to be able to add a delay that allows a 1 or 2 second delay between throwing the snowball so that I cannot spam it.
var projectile : Rigidbody;
var speed = 20;
function Update()
{
if( Input.GetButtonDown( "Fire1" ) )
{
var instantiatedProjectile : Rigidbody = Instantiate(
projectile, transform.position, transform.rotation );
instantiatedProjectile.velocity =
transform.TransformDirection( Vector3( 0, 0, speed ) );
Physics.IgnoreCollision( instantiatedProjectile. collider,
transform.root.collider );
}
}
thanks :)
Answer by mononull · Nov 30, 2012 at 11:37 PM
you can use a timer. create a float variable and in the update say timer+=Time.deltaTime; if the player fired a shot. this is the time since the last update. when the timer reaches a value of 2, meaning 2 seconds have passed since the last shot reset it to 0. So when Fire1 occurs start the timer. change the if statement to (if input.getbuttondown && timer < 2). you could also count down rather than up. if you want to use a timer look at the Time class and particularly Time.deltaTime.
if i were u i would look into coroutines though. not just for this, but they are extremely useful in place of update functions that get called every loop. http://docs.unity3d.com/Documentation/ScriptReference/index.Coroutines_26_Yield.html not a lot at that link. a coroutine is like a regular function but u can hold the return of the function for so many seconds and then run some code when the time is up. you could create a coroutine like function ShotFired() and use it in conjuction with a bool. in this method instantiate the projectile and launch it or whatever. then after those statements say yield WaitForSeconds(2); then set ur bool as a sentinel meaning the player is allowed to fire again. So the bool is CanFire = true. upon firing once the bool changes to false. if(canfire == false) dont let them shoot. but once the first shot coroutine returns after 2 seconds it can switch CanFire to true...letting the player shoot again.
Your answer
Follow this Question
Related Questions
How do I...? [scripting help] 2 Answers
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Simple Timer 2 Answers
Counting Down Timer But My Variable is not reaching Zero ever, Why? 1 Answer
C Sharp Messenger Extended Warning 1 Answer