Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Find and follow nearest object

Discussion in 'Scripting' started by MRTS6, Dec 18, 2021.

  1. MRTS6

    MRTS6

    Joined:
    Aug 25, 2021
    Posts:
    9
    I'm making a game and in my game there are players and there are enemies and I want the enemies to attack the nearest player in range.
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,596
    Well, what have you tried?
     
  3. MRTS6

    MRTS6

    Joined:
    Aug 25, 2021
    Posts:
    9
    I've tried this but it's only focusing on 1 object and it's not good enough.
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class EnemyAI : MonoBehaviour
    5. {
    6.     public Transform target;
    7.     public float within_range;
    8.     public float speed;
    9.     public float min_range;
    10.     // Update is called once per frame
    11.     void Update()
    12.     {
    13.         transform.LookAt(target);
    14.         var distance = Vector3.Distance(target.position, transform.position);
    15.         if (distance <= within_range)
    16.         {
    17.             if (distance >= min_range)
    18.             {
    19.                 transform.position += transform.forward * speed * Time.deltaTime;
    20.             }
    21.         }
    22.     }
    23. }
     
  4. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,385
    1) You need to get a list of all players.

    Search by tag? search by overlap sphere? find by script? have a script that stores all active instances of itself in a easily accessible place like a static collection? There's like a bajillion ways... you just need to get a ref to all of them.

    2) Loop over that collection and do a distance comparison, keeping the smallest one.

    3) Replace 'target' in your EnemyAI with this player's transform.
     
    Kurt-Dekker likes this.