Is there a way to turn off OnTriggerStay?

I need to call OnTriggerStay only once if specific conditions are reached. I have created a script that calls OnTriggerStay and disables the script once the message is sent, but it seems that even though the script is disabled OnTriggerStay is still being called by Unity.

I don’t want to disable the collider because I need to use OnTriggerEnter and OnTriggerExit for other purposes, both functions are in a separated script apart from the one with OnTriggerStay. Disabling and enabling the collider causes CPU spikes.

Any ideas?

public function OnTriggerStay (collider : Collider) {
  if (!this.enabled) {
    Debug.Log("Hi, Im disabled");
  }
  // Some code TODO
  this.enabled = false;
}

Yes, disabling a script only stops the periodic functions (Update, LateUpdate, FixedUpdate) - events called by the collision system still are active.

A simple (and faster) way to avoid OnTriggerStay is to set a boolean variable at OnTriggerEnter and clear it at OnTriggerExit, and call the desired code inside Update or FixedUpdate when this variable is true - like this:

bool inTrigger = false;

void OnTriggerEnter(Collider other){
  inTrigger = true;
  // other code
}

void OnTriggerExit(Collider other){
  inTrigger = false;
  // other code
}

void Update(){
  if (inTrigger){
    // OnTriggerStay code
  }
  // other code
}

There’s a problem, however: if this code is attached to the trigger and two objects enter it, the first to enter sets the variable and the first to exit clears it, thus the second object doesn’t do anything when exiting. A possible solution is to count events instead, like below:

int inTrigger = 0;

void OnTriggerEnter(Collider other){
  inTrigger++;
  // other code
}

void OnTriggerExit(Collider other){
  inTrigger--;
  // other code
}

void Update(){
  if (inTrigger > 0){
    // OnTriggerStay code
  }
  // other code
}

This way, the variable inTrigger is > 0 when there are objects inside the trigger, and only returns to zero when all of them left it.