Hi,
So I wrote a crude script for an object to find all the objects in the game that are tagged with certain tags, there are 5 tags in an array it uses. I don’t like it because it is 2 for loops that run every second per soldier unit in play which could end up being quite a few. However when I run it from within the unity editor the whole thing freezes and I have to terminate the instance of unity and start it again to get anything done. Without this segment of code it works fine.
GameObject[] FindAllBaddies()
{
List<GameObject> objects = new List<GameObject>();
for (int i = 0; i < tags.Length; i++)
{
GameObject[] tmpArray = new GameObject[]{};
tmpArray = GameObject.FindGameObjectsWithTag(tags[i]);
for (i = 0; i < tmpArray.Length; i++)
{
objects.Add(tmpArray[i]);
}
}
return objects.ToArray();
}
Firstly can someone tell me why it is failing so I don’t do it again, secondly is there a better way to write it? Incase it helps after this step there is a piece of code that puts it through a switch statement to get the tag so it can get the owner variable from its script (each object type has a script that both holds it’s operating variables and dictates it’s behavior).
Ah I did not know about that function. It is throwing some null reference exceptions but I think that is my array. It isn’t freezing anymore so problem solved. Thanks heaps mate!
A bit late to the game and stating the fact that I’ve not put much thought to this… but…
Off the top of my head, why not add the objects to a list when they are instantiated, and then use that list of objects to logically sort or test or use?
If you:
GameObject taggedObject = Instantiate(myObject, spawnPosition, spawnRotation) as GameObject;
then you could:
taggedObjectList.Add(taggedObject);
… and this doesn’t have to be a gameObject, it could be a customClass with your tagged object’s data…
You would always have your list of taggedObjects. Your soldiers only need a reference to the list, which could easily be done. You could then process this list as you needed.
You would only need a way to “unregister” any taggedObject if it was destroyed or no longer needed, but you could do that with a .Remove(taggedObject) when needed.