Calling a function only once in Update

Hi everyone, I’m having an inssue with my script here:

var barDisplay : float = 3;
var timeLeft : float = .5;  //amount of time on timer
static var finishTimer = false; //i made this global so you can access from other scripts
static var timerStarted = false;



function OnTriggerEnter (col : Collider){
		if(col.name == "Player")
		
		GameObject.Find("DoubleRockets").GetComponent("gunscript");
		gunscript.initialSpeed += 200;
		timerStarted = true;
		
		
		}
		
			
function Update() {

    if (timerStarted == true)
    	timeLeft -= Time.deltaTime;
	
	if (timeLeft <= 0.0f)  
	{
		GameObject.Find("DoubleRockets").GetComponent("gunscript");
		gunscript.initialSpeed -= 200;
		Destroy(gameObject);
	}
	
}

The problem is that the gunscript.initialSpeed -= 200;
part is being called more than once before the gameobject is destroyed. How can I make sure this function gets called only once?

You could always create a boolean variable equal to false at first and make an if statement which will check if it’s false. Inside the if statement call your function and make the boolean equal to true

static var gunSpeedReduced = false;

if (timeLeft <= 0.0f)  
    {
        GameObject.Find("DoubleRockets").GetComponent("gunscript");

        if(gunSpeedReduced == false)
        {
          gunscript.initialSpeed -= 200;
          gunSpeedReduced = true;
        }
        
        Destroy(gameObject);
    }

bool MyFunctionCalled = false;

void Update()
{
      If(MyFunctionCalled==false)
    {
        MyFunctionCalled = true;
        Do Your Stuff Here And It Will Be Only Done Once !.
    }

}

You should simply be using Invoke() for something like this. Pass it the function to call and the time period and it’ll do the rest for you. You can call this on your component or whatever object you need.

No need to track the time and things manually unless you need to track it in increments, and even then if you need increments use InvokeRepeating() since it’s easily cancelled.

If you want to call the function only once then create your own function or use function start. Anything under the Function Update is called every frame. Which is every second.

void Update()
{

if(anything== 1){

//DoWhatYouWant

anything = anything + 1;

}

}

}