Shoot Timer Wont Reset
if (Input.GetKey(KeyCode.Space))
{
timer -= Time.deltaTime;
if (timer < 0)
{
Rigidbody bull = (Rigidbody)Instantiate(bullet, transform.position, transform.rotation);
bull.AddForce(Vector3.forward * 10f);
timer = 5f;
}
}
This has me stumped. Wondering why my timer isn't resetting to 5 after I shoot? Is there something wrong with my logic?
Thanks!
Is this done in the Update method? If so, it only counts down while you hold Space. Is that how you wanted to do it?
It is done in the update method, and yes that is my intention. Once the timer reaches < 0 it fires and is suppose to reset to 5 (and count down to below 0) to repeat the effect of a "machine gun". Any ideas?
Well i don't see anything wrong with it. It should work unless you disable the script somehow or change the timer again further along the Update. By the way 5 is the starting value too? Because it means 5 seconds (just seems a bit long for a machine gun) and maybe you're just not waiting another 5 seconds?
Are your bullets firing constantly? If I understand Time.deltaTime correctly, a timer of 5 would run down in about half a second at 60 FPS, you may just want a bigger timer amount.
Yeah, the timer set to 5 is just experimental values! Thank you though.
Actually 5 means 5 seconds. Using deltaTime is saying that you don't want to depend on framerate.
Answer by utohaha · May 25, 2016 at 08:47 PM
Okay, weird. I found the problem.
if (timer < 0)
{
Rigidbody bull = (Rigidbody)Instantiate(bullet, transform.position, transform.rotation);
bull.AddForce(Vector3.forward * 10f);
timer = 5f;
}
Unity doesn't read anything after:
bull.AddForce(Vector3.forward * 10f);
I changed it to:
{
timer = 5f;
Rigidbody bull = (Rigidbody)Instantiate(bullet, transform.position, transform.rotation);
bull.AddForce(Vector3.forward * 10f);
}
and now it works fine. Why is this? Is it a bug? (I am using 5.3.1 because too lazy to update right now)
Also throws an InvalidCastException at the force line. $$anonymous$$aybe this is a breakpoint for the code? But it still works? So odd
$$anonymous$$aybe try :
Rigidbody bull = Instantiate(bullet, transform.position, transform.rotation).GetComponent<Rigidbody>();
Yeah that explains it, after an error the script stops to execute. Vintar is right, use GetComponent, or if the object doesn't already have one, AddComponent.
Your answer
Follow this Question
Related Questions
Coroutine, Timer Local vs Class variable difference 0 Answers
How to record lap time for player and AIs? 0 Answers
A StopWatch you can apply values to? 0 Answers
Trouble with coroutine 0 Answers
How do I create a timer. 1 Answer