how to assign an array of targets using overlapSphere?? need help

Hi all,

I have a script attached to enemy/agents that sets them to patrol based off of target GameObjects that
I place in the environment. It currently works, but the current setup finds and uses all GameObjects with
a specific .tag and uses only an amount that I set in the inspector… not really what I want.

What I am trying to do is the following… Spawn an Enemy/Agent that has a script using an OnTriggerEnter and an OverlapShere using in my case a variable named “targetSearchRadius”, assign only the GameObjects with a valid tag/name and within the OverlapSphere as
valid targets.

Below is a piece of code that I am using to send messages to colliders
within an Overlap Sphere. What I am not sure about is how to assign the GameObjects to the HitColliders*.*
Thanks for any help, it is really appreciated!
-Kory
```csharp

  •    void OnTriggerEnter(Collider hit){
          Collider[] hitColliders = Physics.OverlapSphere (gameObject.transform.position, targetSearchRadius);
          int i = 0;
          while (i < hitColliders.Length){
              hitColliders [i] = Collider(Bla,Bla,Bla);
              i++;
          }
      }*
    

```

Each of the Collider objects returned by your call to OverlapSphere has both a .tag field and a .gameObject.

You can iterate them (like you are with the while loop) and check the .tag field, then if it is you can access the .gameObject field

if (hitColliders[i].tag == "WhateverTagYoureLookingFor")
{
  hitColliders[i].gameObject ... // do what you want here with the GameObject? Maybe spawn something here? call .GetComponent to find a script, etc.
}

Just be sure to leave your i++ outside of the above if statement or else you’ll have a deadlock.

1 Like