Search Unity

script to find nearest game object with tag

Discussion in 'Scripting' started by Imp_Lord, May 26, 2017.

  1. Imp_Lord

    Imp_Lord

    Joined:
    Jun 18, 2016
    Posts:
    6
    so I'm making a guiding system to help the player find the closest off screen game object tagged "Pick Up" and was wondering if there was an easy way to accomplish this. note that new pick ups are spawning in every few seconds so it needs to be able to update itself constantly. any suggestions?
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,521
  3. Imp_Lord

    Imp_Lord

    Joined:
    Jun 18, 2016
    Posts:
    6
    I cant seem to get one working. every example i see shows the use of a Collider array but when I put
    "Collider[] hitColliders" Collider doesn't light up like it does in the examples.
     
  4. Dolzen

    Dolzen

    Joined:
    Mar 26, 2014
    Posts:
    90
    Post your code
     
  5. Imp_Lord

    Imp_Lord

    Joined:
    Jun 18, 2016
    Posts:
    6
    I don't have any real code for this cause its the first part of the script needed to make everything else on. im just trying to get this example script working first and Collider[] isnt working.

    using UnityEngine;
    using System.Collections;

    public class ExampleClass : MonoBehaviour
    {
    void ExplosionDamage(Vector3 center, float radius)
    {
    Collider[] hitColliders = Physics.OverlapSphere(center, radius);
    int i = 0;
    while (i < hitColliders.Length)
    {
    hitColliders.SendMessage("AddDamage");
    i++;
    }
    }
    }
     
  6. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    Well, if that's the entirety of the script, it can't possibly be working because the method is never called.

    Please read the pinned thread about inserting code properly into the forums.

    and this:
    Code (csharp):
    1.  void Update() {
    2.    if (Input.GetKeyUp(KeyCode.A)) ExplosionDamage(transform.position, 20);
    3. }
    4. // change explosion dmg so you just print out the array length and/or each object's name or something, since you probably don't have something for "SendMessage" to work with anyways
    5.  
    Then put it on your character, click play and click the 'A' key ;)