Search Unity

Finding objects in an area?

Discussion in 'Scripting' started by Marscaleb, Oct 21, 2021.

  1. Marscaleb

    Marscaleb

    Joined:
    Jan 7, 2014
    Posts:
    1,037
    I'm setting up my enemies to be spawned into existence when the player triggers particular scripts, typically by touching some trigger volume. But I'm also setting up some enemies that are going to depend upon specific paths set into the level. This means I need a way for those enemies to be able to find what path they need to associate with autonomously, as I can't just drop a reference in the inspector for a object that was just instantiated into the scene.

    I'm open to suggestions as to how I could do this.

    I'm thinking it could work simply enough if I place the spawn-point close to a node on the path, and then the enemy can just look for path nodes near it. But how?
    I couldn't use colliders and triggers for this, at least not without making something convoluted. There are no colliders on the path nodes, and if I tried to add trigger colliders to the path node, well, triggers can't collide with triggers.

    Is there some kind of universal function to search for gameObjects within a given area?
    So I could, say, search for all game objects within a sphere around the enemy, and then iterate through those objects until I find one with a specfic script on it, or maybe a custom tag. If I set it to search within say a 1 unit sphere, there shouldn't be more than a couple objects to iterate through, (especially if I could ignore the object the script is attached to.)
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,648
    If your objects have Colliders, you can do things like OverlapSphere or OverlapBox to check for colliders in an area.
     
  3. exiguous

    exiguous

    Joined:
    Nov 21, 2010
    Posts:
    1,749
    I would create a PathManager which holds a list of all GameObjects with a PathScript. The PathScript instance registers itself with that manager (via a static method, singleton, you name it) in Start. It could also contain an "index" of the path it belongs to, it's neighbour(s) etc..
    So if you want to create a path you just put some objects with that script in place. And the enemies can query the pathmanager for the closest point of their path.
    I would not (ab)use physics system for such things since the calculation only has to be done once (if I understand your scenario correctly ofc). And when you have a list of all PathObjects in a certain range you still need to make a path out of it. Does that happen during design time or are the waypoints also just spawned at runtime?
     
    Marscaleb likes this.
  4. Marscaleb

    Marscaleb

    Joined:
    Jan 7, 2014
    Posts:
    1,037
    The paths will be saved as part of the map (scene) data, and loaded in when the player in in that area.
     
    exiguous likes this.