Search Unity

GameObject.FindGameObjectWithTag. Some problems

Discussion in 'Scripting' started by zreek17, Jan 11, 2014.

  1. zreek17

    zreek17

    Joined:
    Jun 2, 2013
    Posts:
    21
    Hello guys! I am using suc good command in my script - GameObject.FindGameObjectWithTag.
    The situation is:
    Imagine a character, player, and for example, his transform.position.z = 0.
    Than an enemy is respawned, his transform.position.z = 20, tagged "Enemy".
    Than a second enemy is respawned, his transform.position.z = 40, tagged "Enemy".

    After that the script is used: we need to find the nearest enemy position, so I use GameObject.FindGameObjectWithTag.
    But it finds an enemy, who was respawned at last, it is second enemy. But I need the nearest Enemy to stay selected until he is destroyed.

    I know, that it is necessary to use FindGameObjectsWithTag, but don't know how to use it correctly to find the lowest Z.position.
    Maybe you could help me with this problem?
     
  2. jgodfrey

    jgodfrey

    Joined:
    Nov 14, 2009
    Posts:
    564
    You probably want the FindGameObjectsWithTag method:

    https://docs.unity3d.com/Documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html

    That returns an array containing *all* game objects matching the specified tag. From there, you simply need to loop through the returned objects, calculate the distance between your character and the current object (probably using Vector3.Distance), always remembering the "closest" object. Then when finished with the distance loop, do whatever is appropriate with the closest object.

    Jeff
     
  3. softwizz

    softwizz

    Joined:
    Mar 12, 2011
    Posts:
    793
    Well then, if you check the link jgodfrey posted you will notice there is an example
    // Print the name of the closest enemy

    this actually has function FindClosestEnemy ()
     
  4. zreek17

    zreek17

    Joined:
    Jun 2, 2013
    Posts:
    21
    Oh my God, guys, it is really amazing! How could I miss such a simple thing :))
    Thank you very much!