如何获取相应的变量名称为其对应的值C#

时间:2018-06-19 10:34:06

标签: c# unity3d

我有这个脚本。我试图找出玩家与地图四个角落之间的距离。它成功返回每个角落之间的距离(距离C1 =角落1等),并找出离玩家最远的角落。

我正在尝试将该角落的游戏对象名称作为" largestDistanceName"。与最远距离对应的角落。

EG。如果DistanceC3是最远的,则使最大距离名称等于游戏对象Corner3等等。

我不知道该怎么做。谢谢

  public GameObject Corner1;
  public GameObject Corner2;
  public GameObject Corner3;
  public GameObject Corner4;


  public float distanceC1;
  public float distanceC2;
  public float distanceC3;
  public float distanceC4;




    distanceC1 =Vector3.Distance(Corner1.transform.position,ThePlayer.transform.position);
    distanceC2 =Vector3.Distance(Corner2.transform.position,ThePlayer.transform.position);
    distanceC3 =Vector3.Distance(Corner3.transform.position,ThePlayer.transform.position);
    distanceC4 =Vector3.Distance(Corner4.transform.position,ThePlayer.transform.position);
    float[] DistanceArray = {distanceC1, distanceC2, distanceC3, distanceC4};
    float maxValueDistance = DistanceArray.Max();
    LargestDistance = maxValueDistance;
    LargestDistanceName = INSERT SCRIPT THAT FETCHES CornerX corresponding to the distance. 

2 个答案:

答案 0 :(得分:2)

public Transform GetFarthestCorner( Transform from, params Transform[] corners )
{
    Transform farthestCorner = null ;
    float maxDistance = -1 ;

    for( int cornerIndex = 0 ; cornerIndex < corners.Length ; ++cornerIndex )
    {
        float distance = ( corners[cornerIndex].position - from.position ).sqrMagnitude ;
        if( distance > maxDistance )
        {
            farthestCorner = corners[cornerIndex];
            maxDistance = distance ;
        }
    }

    return farthestCorner ;
}

使用方法:

Transform farthestCorner = GetFarthestCorner( ThePlayer.transform, Corner1.transform, Corner2.transform, Corner3.transform, Corner4.transform ) ;
float distance = Vector3.Distance( farthestCorner.position, ThePlayer.transform.position ) ;

答案 1 :(得分:1)

您的所有代码都可以替换为简单的LINQ查询

// assuming you have...
List<GameObject> corners;
GameObject player;

var closestCornerName = corners
    // order collection of corners by the distance to player, descending
    .OrderByDescending(corner =>
        Vector3.Distance(corner.transform.position, player.transform.position)) 
    // take the first (furthest) one
    .First()
    // take its name
    .name;