I've read that FindGameObjectsWithTag is quite a slow function. In my scene I call this function quite frequently the way seen in the code below.
Would it be a better practice to create a GameObject with a script component storing a static builtin array and adding every instance of the object at the time of instantiation and removing them when destroyed?
function FindTarget () : GameObject
{
var allAtoms : GameObject [];
allAtoms = GameObject.FindGameObjectsWithTag ("atom");
var target : GameObject;
var distance = Mathf.Infinity;
var ownPosition = transform.position;
for (var atom : GameObject in allAtoms)
{
var atomScript : Atom = atom.GetComponent (Atom) as Atom;
if (charge == atomScript.charge * (-1) && atomScript.canMerge == true)
{
var difference = atom.transform.position - ownPosition;
var currentDistance = difference.sqrMagnitude;
if (currentDistance < distance)
{
target = atom;
distance = currentDistance;
}
}
}
return target;
}