- Home /
 
               Question by 
               Musty · Jan 18, 2015 at 01:04 PM · 
                arraymovetowardsclosest  
              
 
              Move an object towards closest enemy.
Hey guys I found a code in the unity reference that finds the closest object to the player and im trying to figure out how i could move the object towards closest object in the array. Everything i tried gives me an error so far. I was wondering if anyone could quickly point me to the right direction.
 using UnityEngine;
 using System.Collections;
 
 public class projectileMove : MonoBehaviour 
 {
     float projectileSpeed = 0;
     void Update()
     {
         float projSpeed = projectileSpeed * Time.deltaTime;
         //FindClosestEnemy();
         print (FindClosestEnemy().name);
         //transform.position = Vector3.MoveTowards(transform.position, FindClosestEnemy().position, projSpeed);
     }
     GameObject FindClosestEnemy()
     {
         GameObject[] gos;
         gos = GameObject.FindGameObjectsWithTag("Enemy");
         GameObject closest = null;
         float distance = Mathf.Infinity;
         Vector3 position = transform.position;
         foreach (GameObject go in gos) 
         {
             Vector3 diff = go.transform.position - position;
             float curDistance = diff.sqrMagnitude;
             if (curDistance < distance) 
             {
                 closest = go;
                 distance = curDistance;
             }
         }
         return closest;
     }
 }
               Comment
              
 
               
              Answer by jabez · Jan 18, 2015 at 01:32 PM
Hello, Try using vector3 distance.
 if (gos.Length > 0){
 GameObject ClosestEnemy = gos[0];
 
 foreach (GameObject go in gos)
 {
 if (Vector3.Distance(gos.transform.position, transform.position) < Vector3.Distance(ClosestEnemy.transform.position, transform.position)){
 ClosestEnemy = gos;
 }
 }
 }
     
     
Hopefully that helps it might even be the other way around so instead of < it's >, I don't know i didn't test it.
Your answer
 
 
             Follow this Question
Related Questions
is an Array the most efficent way of finding the closest gameobject? 1 Answer
Find Closest Object by Name 0 Answers
Select/attack closest target array 1 Answer
Homing missile: choosing a new target 1 Answer
How To Find the Closest Object 0 Answers
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                