- Home /
FindGameObjectsWithTag alternative for better perfomance
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;
}
Answer by StephanK · Nov 12, 2010 at 12:02 AM
Are you experiencing performance problems? If not you can just leave it like it is. If you want to speed up things I would use a singleton manager with an atoms array or list (depending on what you need to do with them). Then all you have to do is add a line to the Start() of your atoms that registers itself with the manager and unregisters in OnDisable(). This way you will always have an up to date array/list of atoms and you don't need to recreate it every time.
Your answer
![](https://koobas.hobune.stream/wayback/20220613082807im_/https://answers.unity.com/themes/thub/images/avi.jpg)