find closest gameobject unity
GameObject FindClosestTarget(string trgt) { Vector3 position = transform.position; return GameObject.FindGameObjectsWithTag(trgt) .OrderBy(o => (o.transform.position - position).sqrMagnitude) .FirstOrDefault(); }
find closest gameobject unity
GameObject FindClosestTarget(string trgt) { Vector3 position = transform.position; return GameObject.FindGameObjectsWithTag(trgt) .OrderBy(o => (o.transform.position - position).sqrMagnitude) .FirstOrDefault(); }
how to find closest object with tag unity
// Find the name of the closest enemyusing UnityEngine; using System.Collections;public class ExampleClass : MonoBehaviour { public 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; } }
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us