I have this code here where I use a Mathhf.min, and it works out what the closest object is.
But it only spits out the distance of what is closest, i want to know what object that is, can
I put something in here to get back which of these object is the minimum and then so i can use it in a if statement?
// Create a new list containing the PlayerMovement scripts
System.Collections.Generic.List<PlayerMovement> list = new System.Collections.Generic.List<PlayerMovement>()
{
player1.GetComponent<PlayerMovement>(),
player2.GetComponent<PlayerMovement>(),
player3.GetComponent<PlayerMovement>()
};
// Sort the list according to the `distToPuck`, in the ascending order.
// The Sort method can take as argument a function used to compare the elements in the list
// I've created an anonymous function to compare the distToPuck
list.Sort( ( PlayerMovement p1, PlayerMovement p2 ) =>
{
if ( Mathf.Approximately( p1.distToPuck, p2.distToPuck ) )
return 0;
else
return (int) Mathf.Sign( p1.distToPuck - p2.distToPuck );
} ) ;
// The list is now sorted. The first element of the list is the one with the smallest distToPuck value
PlayerMovement bestPlayerMovement = list[0];
2nd solution :
public PlayerMovement GetBestPlayerMovement( params PlayerMovement[] playerMovements )
{
// Consider the "best" as the 1st one of the array
PlayerMovement best = playerMovements[0];
// Save the distToPuck as the "best" one (the smallest one)
float minValue = best.distToPuck ;
// Loop through the array in order to find the playerMovement with the smallest distToPuckValue
for ( int i = 1 ; i < playerMovements.Length ; i++ )
{
if ( playerMovements*.distToPuck < minValue )*
{ best = playerMovements*;* minValue = playerMovements*.distToPuck;* } } return best ; } And call it : PlayerMovement playerMovement = GetBestPlayerMovement( player1.GetComponent(), player2.GetComponent(), player3.GetComponent() ) ;