Optimization: trigger or distance

Hello everyone!

I have a question about optimization. The situation: I have, in about every scenes, at least 150 objects of same goal (they can be compared to collectibles). At the moment, the scenes aren’t made; just designed.
Each of these items contains a sphere trigger on them. I was thinking about optimizing them by only calculating the squared distance (Vector3.sqrMagnitude) with the player and do things when it is close enough. What do you think about that optimization. Would it be better? Or am I completely out of the track? Also, they only interact with the player and they do not move at all.

I could even split them in 4(?) pack and only one pack will update each update. This little add will increase the cost in performance on each of these objects. Something like:

//In Update()
--m_nbFrameUntilUpdate;
if (m_nbFrameUntilUpdate == 0)
{
    m_nbFrameUntilUpdate = 4;
   if ( (player.position - transform.position).sqrMagnitude <= s_distance )
   {
        //Code that would be in OnTriggerStay
   }
}

So, I would like some advices/feedback on that kind of change or even, a better idea. :smile:

Thank you,
Phil

you could try vector3.distance

Using triggers would definitely be more optimized than calculating vector3.distance or sqrMagnitude every frame.

better trigger yes.

Perfect, I’ll keep triggers then.

@ handsomePATT, Vector3.Distance is doing “(VectorSource - VectorDestination).magnitude” if i’m not wrong. And calculating the square root of Vector3.sqrMagnitude (to obtain .magnitude) is costy, especially if calculated every frame many times. Vector3.Distance can be good if you want to know the distance from two vector but not that good if you only want to compare positions.