OnTriggerStay makes game slow (javascript)

Hello:

We created a Particles class (with its attributes, etc.)

We create X amount of particles (cubes) and store them in an array, aParticles. This will allow us to check/modify values (positions, etc.) of each individual particle.

Now, on our PLAYER (a cylinder), we created a spherical collider. When it collides with one of the particles, this ones (the cubes) should be attracted to the PLAYER.

The code is as follow:

function OnTriggerStay(collision : Collider) {
 
 for(i=0; i<aParticles.length; i++)
{   
    //Calculate and normalize EACH particle's direction
    var dir = aParticles*.cube.transform.position - transform.position;*

dir = dir.normalized;
aParticles_.cube.rigidbody.AddForce(-dir * force);_

}
}
Notice that I instance the particles form the aParticles array, which has a “cube” attribute (which, in fact, has the cube object)
Now, OnTriggerStay, should check the collision every frame and if there are objects inside, do the code I posted (attract the cubes to the PLAYER. The script is attached to the player).
Now, for some reason, if I put many particles (let’s say 20) the game get VERY slow. 20 is nothing. If I put 5, it runs OK.
Could you recommend me something?
EDIT:
Here is a way to do the described behavior without the OnTriggerStay:
* var radius:Number = 10;*

* …*
* (in the Update function)*
* for(i=0; i<aParticles.length; i++)*
* { *
_ var distance = Vector3.Distance(player.transform.position, aParticles*.cube.transform.position);
if (distance < radius) {
var dir = aParticles.cube.transform.position - transform.position;
dir = dir.normalized;
aParticles.cube.rigidbody.AddForce(-dir * force);
}
}*_

So you’re using physics calculations, in a loop, calculated every frame - those three things are pretty much guaranteed to make your game slow whatever… :slight_smile:

However, one thing strikes me as odd - you said that “when the player collides with one of the particles” - so the particles themselves have all got individual colliders on them? In which case, why are you looping through the aParticles array in the OnTriggerStay function? OnTriggerStay will get called indivudally for each particle that is colliding with the player, so to also loop through every particle seems like double-processing to me…

I don’t use OnTriggerStay() much, but it might be more efficient to maintain your own list of colliders currently within the trigger zone (adding/removing them manually based on OnTriggerEnter and OnTriggerExit), which wouldn’t need to be refreshed every frame, as in Keeping Track of Targets in a Trigger | Alastair Aitchison