0

I want code to check if target is alive, and if yes shoot at it. I want to check it all the time, and shoot all the time, The only problem is that checks can be made anytime u want, but shooting must have limits of fire per second. I mean u check the target all the time, but when u decide to shoot, bullets will fire one after another with some delays. And also when u realize that target is dead u stop shooting at the same time.

void Update()
{
   StartCoroutine(Shoot(currentTarget, 1f));
}

IEnumerator Shoot(Collider currentTarget, float delayTime)
{
    yield return new WaitForSeconds(delayTime);
    if (currentTarget != null)
    {
         .......
    }
}

This code starts to shoot but with no delays between shooting.

David
  • 4,332
  • 13
  • 54
  • 93
  • 2
    never use coroutines. use Invoke or InvokeRepeating – Fattie Mar 04 '16 at 22:32
  • I did but invoke method could not be called because shoot method had parameter inside. Invoke("Shoot(currentTarget)", 3 ); This code was not invoking shoot – David Mar 04 '16 at 22:34
  • Few questions for you. What do you mean by alive? I assume that currentTarget is the target. How do you know when the target is dead? – Programmer Mar 04 '16 at 22:34
  • I actually *would not put* the currentTarget as an argument to the Shoot function – Fattie Mar 04 '16 at 22:36
  • @JoeBlow why not use coroutines? Unity's virtual reality samples heavily uses them and not invoke – Martin Dawson Mar 04 '16 at 23:45
  • 1
    @MartinMazzaDawson Never never ever use coroutines. They teach bad habits from the point of view as a c# developer and will lead to a lynching if you take a regular c# job –  Mar 05 '16 at 00:40

1 Answers1

2
InvokeRepeating( "PossiblyShoot" , 1f, 1f );

private void PossiblyShoot()
   {
   1. check if target still exists
   2. if it exists shoot at it
   }
Fattie
  • 27,874
  • 70
  • 431
  • 719
  • Perfect. Also I had to move Invoke from Update function to start and now it's working fine! Thanks! – David Mar 04 '16 at 22:48
  • 1
    lol no worries .. enjoy yourself. don't believe anything you see in Unity doco – Fattie Mar 05 '16 at 02:05