Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- public class Closest : MonoBehaviour
- {
- [Tooltip ( "The array of objects to check." )]
- public Transform [ ] PArray;
- public Transform ClosestP { get; private set; } = null;
- [Tooltip("A default of '1' indicates that we check once a second for the closest object.")]
- public float CheckInterval = 1;
- private float timer = 0;
- private void Start ( )
- {
- // Make sure that we calculate the distance once at the very beginning.
- timer = CheckInterval + float.Epsilon;
- }
- void Update()
- {
- timer += Time.deltaTime;
- if ( timer >= CheckInterval )
- {
- timer -= CheckInterval;
- var closestPIndex = ClosestPIndex ( );
- if ( closestPIndex >= 0 )
- ClosestP = PArray [ closestPIndex ];
- // ClosestP is now your closest object.
- }
- }
- private int ClosestPIndex ( )
- {
- var closestIndex = -1;
- var closestDistance = float.MaxValue;
- for ( int i = 0; i < PArray.Length; i++ )
- {
- var sqrMagnitude = ( transform.position - PArray [ i ].position ).sqrMagnitude;
- if ( sqrMagnitude < closestDistance )
- {
- closestDistance = sqrMagnitude;
- closestIndex = i;
- }
- }
- return closestIndex;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment