Detect Closest Enemy/anything in unity3d tutorial

Subscribers:
1,110
Published on ● Video Link: https://www.youtube.com/watch?v=FgLtCar2DfM



Category:
Tutorial
Duration: 3:03
2,125 views
52


Code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DetectClosest : MonoBehaviour
{

public string tagToDetect = "Enemy";
public GameObject[] allEnemies;
public GameObject closestEnemy;
// Start is called before the first frame update
void Start()
{
allEnemies = GameObject.FindGameObjectsWithTag(tagToDetect);
}




// Update is called once per frame
void Update()
{
closestEnemy = ClosestEnemy();
print(closestEnemy.name);
}


GameObject ClosestEnemy()
{

GameObject closestHere = gameObject;
float leastDistance = Mathf.Infinity;

foreach (var enemy in allEnemies)
{

float distanceHere = Vector3.Distance(transform.position,enemy.transform.position);

if (distanceHere less than sign leastDistance)
{
leastDistance = distanceHere;
closestHere = enemy;
}

}




return closestHere;
}

}







Tags:
unity
unity3d
learn unity
unity tutorials
detect closest enemy in unity
unity detection
sorting enemies
detecting enemies
detecting enemies in unity