Closest#
Collections / Closest
Can Read
Cannot Write
Description#
The Game Object of a collection that is nearest to a position
Parameters#
| Name | Description |
|---|---|
| Collection | The collection the Game Object is picked from |
| Position | The position distances are measured from |
Code#
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
using VisualScript.Icons;
namespace VisualScript.Runtime
{
[Get]
[Title("Closest")]
[Category("Collections/Closest")]
[Description("The Game Object of a collection that is nearest to a position")]
[Image(typeof(IconCompass), ColorTheme.Type.Teal, typeof(BadgeArrowDown))]
[Parameter("Collection", "The collection the Game Object is picked from")]
[Parameter("Position", "The position distances are measured from")]
[Keywords("Near", "Distance", "Sort", "Order", "Pick", "List", "Array")]
[Serializable]
public class TypeGameObjectCollectionClosest : TypeGameObject
{
[SerializeField] private GetCollectionGameObjects m_Collection = new GetCollectionGameObjects();
[SerializeField] private GetVector3 m_Position = new GetVector3();
public override GameObject Get(Args args)
{
List<GameObject> buffer = ListPool<GameObject>.Get();
try
{
this.m_Collection.Get(args, buffer);
Vector3 origin = this.m_Position.Get(args);
GameObject result = null;
float bestDistance = 0f;
bool hasResult = false;
foreach (GameObject gameObject in buffer)
{
if (gameObject == null) continue;
float distance = (gameObject.transform.position - origin).sqrMagnitude;
if (hasResult && !(distance < bestDistance)) continue;
bestDistance = distance;
result = gameObject;
hasResult = true;
}
return result;
}
finally
{
ListPool<GameObject>.Release(buffer);
}
}
public override string ToString()
{
return $"Closest of {this.m_Collection}";
}
protected override SubscriptionMode Subscription => SubscriptionMode.OnChange;
}
}