- Home /
Best way to access game objects
I am currently working on a 2d game in which there are 2 players that have an "army" each. I want to detect when a unit of an army is in attack range of one of the enemy's unit. So I need to iterate through all the enemy units and select one that is in range.
What is the best way to do that ? There are a couple of methods that I think are a little slow for my taste and I would like to avoid. Like GameObject.Find() and GetComponent()..
I tried to create 2 empty game objects RedTeam and BlueTeam and added all units as children of these, but I can't seem to find a way to easily access them. I used getComponentsInChildren, but this seems to return the component in the parent too and I'm kind of scared that this method is "eating up" too much.
Transform getNextUnitInRange ()
{
Transform[] enemyUnitsTransforms = otherTeam.GetComponentsInChildren<Transform> ();
foreach (Transform enemyTransform in enemyUnitsTransforms) {
if (Mathf.Abs (transform.position.x - enemyTransform.position.x) <= range) {
Debug.Log(transform.position.x + " " +enemyTransform.position.x);
return enemyTransform;
}
}
return null;
}
Should I make a list of somekind with the units and if so where should I store it so it's easily accessible ?
This is my first game in Unity, but I worked with other 2d game engines.
there are perfect articles about this for beginners at
unityGE$$anonymous$$S.com
it is a very common question
Cheers!