- Home /
Get parent/root objects in scene?
Hey. I've recently been redoing a lot of my old code to get a more polished game. Among others, I've scrapped my damage colliders and am now using my ragdoll colliders instead. The improvements are many.
However, this has required me to give all components in my enemies the "Enemy" tag.
I have an optimized means of checking if enemies can see the player, by having a child of the Player object get everything with an Enemy tag in the level, stick it into an array and raycast towards one enemy per frame. Which worked perfectly when only the shell object had an "enemy" tag, but now it returns an array consisting of hundreds, if not thousands of entries.
So my question is, how do you modify this:
ActiveEnemies = GameObject.FindGameObjectsWithTag("Enemy");
To only find root objects?
$$anonymous$$ore of an aside than a direct answer to the question, as I think you've got something of an XY problem here.
If you've got thousands of these things, then trying to optimise a searching approach to this is only going to make limited improvements, and before long you'd probably be looking at the same problem again.
Ins$$anonymous$$d I would strongly recommend you move away from using Find and Tags for this. Ins$$anonymous$$d, have an Enemy$$anonymous$$anager object of some sort that Enemies can register/deregister themselves with, and query that object when you want to know stuff about what enemies there are at any point. This way the work of keeping track is distributed across the times when enemies change, rather than focussed at the point(s) where you need the information.
Answer by Snyper_Labs · Aug 30, 2019 at 01:41 PM
@Hogge The way you want it sounds overly complicated and can significantly degrade performance.
Here's what I would do: Give the "Enemy" tag only to the parent enemy gameobject. Give it a Capsule Collider (or any collider that fits) and set it as trigger (that way, it won't affect any bullet collision or the ragdoll). Make sure all the ragdoll colliders come inside this trigger collider.
ActiveEnemies = GameObject.FindGameObjectsWithTag("Enemy");
Now ActiveEnemies will have all the Enemy gameobjects. Here is a function that will return the number of Enemies in front of you within 100 units. (You can change this to raycast all the gameobjects in ActiveEnemies).
int CheckSight()
{
int EnemySight = 0;
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.forward, out hit, 100))
{
if(hit.collider.gameObject.tag == "Enemy")
EnemySight++;
}
return EnemySight();
}
Feel free to point out any mistakes.