- Home /
Calling a function only once whenever conditions are correct
I have code which builds up charge while a button is held down and then I want it to execute a function only once. This is within a function called ScanInput() which is called from Update()
while(Input.GetButton("Fire1"))// && (Time.deltaTime > nextFire)) { //Add to the charge as long as the // user is holding the button chargeLevel += Time.deltaTime * chargeSpeed; firedMissile = false; firePlayer001Missile(firedMissile); yield; }
chargeLevel = 0.0;
Heres the code for the function firePlayer001Missile
function firePlayer001Missile(firedMissile)
{
if(!firedMissile)
{
var player001Missile = new Instantiate(currentMissileType, GameObject.Find("Player001ShotSpawnPoint001").transform.position,Quaternion.identity);
currentMissileType.transform.Translate(0,shootForce*Time.deltaTime,0);
player001Missile.rigidbody.AddForce(transform.up*shootForce);
bulletCount++;
firedMissile=true;
}
return firedMissile;
}
As it is now, it fires a barrage of bullets which I think is equal to the number of calls to the function firePlayer001Missile; I want it to fire only one bullet after the fire button has been held down.
check GetButtonDown and GetButtonUp, also I prolly wouldn't use a coroutine for this
You changed it from the code I gave you in a previous question. the fired$$anonymous$$issle should go after the while loop if you haven't changed the design, which it looks like you haven't. @$$anonymous$$aggot, There is nothing wrong with the coroutine. It would work the same as having an if statement and a few other bools. See the original answer http://answers.unity3d.com/questions/18013/power-up-weapon-shot-before-releasing-and-resetting-power/18015#18015
Answer by maggot · Nov 16, 2011 at 01:05 PM
I got this working by having a bool set to false. Then an If condition for false on the bool (and it always is false the first time the code is run), followed by the conditional code I want to run once and ending by setting the bool to true.
Your answer
Follow this Question
Related Questions
Different colored jet streaks from fire particle system 2 Answers
Trouble with script to fire a bullet from a handgun 1 Answer
C# RayCast Fire Cooldown DeltaTime Help 1 Answer
How to make extinguish? 1 Answer
Bullets won't fire? 0 Answers