Hello!I’m pretty new to Unity 3d and i got a problem :
if (Input.GetKey (“r”))
{
animation.Play (“reload”);
Shoot.Bullets = 35;
}
//firstly,“Bullets” is a static var placed in another script (“Shoot”) and it defines the number of the bullets.Well,everything works fine but when i press “R” it plays the animation AND in the same time i can shoot.In real life you can shoot only after the gun is loaded.So i’m wodering how the heck can i tell Unity to Wait 3 seconds before i can shoot,but play the animation “Reload” in the moment i pressed the button
i get a bunch of errors because of my other scripts :? sorry,i should to show you my other scripts,but they were pretty long.However i squeezed my brain to the last drop and thanks to your brilliant ideea ("Just keep track of when you shot and ignore shoot requests until enough time has passed.
"):idea: :idea: i managed to write this code(works perfectly) and sorry,it sounds newbish (i know it could be written in less lines):
var canShoot : boolean = false;
var mister : float = 0;
You’re making things way too complicated. Why have a boolean AND a time value.
It helps when thinking about your code (I think) to give variables immediately meaningful names, e.g. “canShoot” being boolean makes sense, but what does “mister” mean?
Instead of canShoot, I’d name the variable “cycleTime”. If your weapon has positive cycleTime then it’s still recovering from being fired. No boolean required. (This was how Vicenti was using “canShoot”.)
PseudoCode:
if ( player_has_trigger_down AND cycle_time <= ZERO ) then
FIRE
set cycle_time to amount of time weapon takes to reload
else
subtract elapsed time from cycle_time
end if
For enemies it’s better to simply use a coroutine:
function Start(){
fire_at_will();
}
function fire_at_will(){
while( true ){
yield new WaitForSeconds( weapon_reload_time );
if ( want_to_fire() ){
fire();
}
}
}
this is conceptually simpler and lighter on the CPU than having using Update or FixedUpdate to handle firing, and AIs don’t complain if their controls suck
For a rough comparison, if you have 10 AIs with a 0.25s cycletime weapon, fire_at_will is executing 40 times per second, vs. say 600 times for at 60fps using Update(). And if the AI is doing a bunch of collision checking to decide if it wants to shoot, those calls to “want_to_fire()” could be quite expensive.
Alternately, you could use animation events to fire off a function that sets your canShoot variable to false and true, respectively (set to false at the beginning of the reload animation, true at the end).
Yeah,thanks…i’ll try it out…but as i said,i’m new and i didn’t knew exacly that “Update” calls that function milions of times :? I got used to use GameStudio A7 scripting :? but things are different here