Search Unity

Find gameobjects with tag in a specific zone

Discussion in 'Scripting' started by MikeyJY, Apr 21, 2020.

  1. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    Is there any way to use GameObject.FindObjectsWithTag() in a specific world zone without looping trough all and verify each of them.

    I want to do this without if statement inside foreach/for.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Can you explain what you mean by "zone"?
     
    matkoniecz likes this.
  3. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    Sorry for late reply. By zone I mean a cube defined by Vector3 corner1 and Vector3 corner2. What inside that cube is in "zone"
     
  4. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    upload_2020-4-22_1-58-41.png The 2 black points are the 2 Vector3
     
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Off the top of my head.... Have a trigger collider encompass the entirety of this "zone". When entering the trigger, any GameObject with the tag you're interested in is added to a list. On exit from the trigger they are removed from the list. Then you don't even need to do FindObjectsWithTag at all, since you have a list available all the time.

    Instead of using trigger colliders, you could just every few seconds have each object figure out which zone they are in, and add/remove themselves from appropriate zone lists. You'd use the lists the same, but maintain them differently.
     
  6. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    Thanks, but some of the objects are in the zone even in the scene view, is OnTriggerEnter called if an object is in trigger before Start()?
     
  7. kdgalla

    kdgalla

    Joined:
    Mar 15, 2013
    Posts:
    4,638
  8. MikeyJY

    MikeyJY

    Joined:
    Mar 2, 2018
    Posts:
    530
    Nice thank, you