Play method only ONCE when detected by the update function

It seems like there should be a pretty simple solution to this problem I’m having but I can not figure it out no matter how hard I try. I’m just trying to make it so that once the update method gets to the “applykillforce();” method (in line 41), it only runs it once, and never gets played again. Right now it runs it over and over again, which is not what I want (because it makes the enemy spaz out).

If anyone has a solution, it would be greatly appreciated, as I have been stuck on this for awhile.

BTW I am new to coding so if you guys could be specific and try to keep it simple for me that would also be great.

If you just want to run it once, perhaps putting this in your start function would be better served.

void Start(){
if(Peeker.GetCompenent<PeekerDie>() != null){
   if(Peeker.GetCompenent<PeekerDie>().enable == true){
    applykillforce();       
    }
  }
}

or you could setup a bool to trigger it once while keeping it in the update sequence.

 bool runOnce;
    void Start(){
    runOnce = false;
    }
    void Update(){
         if(runOnce == false){
             if(Peeker.GetCompenent<PeekerDie>() != null){
                  if(Peeker.GetCompenent<PeekerDie>().enable == true){
                   applykillforce();
                   runOnce = true;
    }
    }
}
}

Setting up a bool is a good way to do what you want. But if you came across a situation that required you to call the function twice, three , 4 … etc. times. I think this is a better way to approach it. And btw your right there is a simple way. I don’t know why people are bringing Coroutines into this. All you have to do is make a int variable count and set it equal to 0 in the beginning. Then when you call your function check if count is equal to 0 if it is then call the function and add one to count. Now the function wont be called again because count doesnt equal 0 anymore. Here’s the code hope it helps!

int count = 0;
private void Update
{
    if( count == 0 && Peeker.GetComponent<PeekerDie>().enable == true){
        count++; // now count is 1 , so next time the if statement will return false and your code wont run more than once.
        applykillforce();
    }
}

void applykillforce()
{
    GetComponentInChildren<Rigidbody>().AddForce(-transform.forward * 16000);
}