使用Array.Sort仅对元素排序而不对索引号排序吗?

时间:2018-12-11 18:26:42

标签: c# arrays sorting unity3d indexof

首先快速总结一下我的代码。

在这里,我有两个数组,一个GameObject和一个float数组。

public class PlaceManager : MonoBehaviour
{
private GameObject[] playerList;
private float[] distanceValue;

在开始时,我调用FindAllPlayers函数,在更新时,我调用两个函数。

void Start()
{
    FindAllPlayers();
}
void Update()
{
    FindPlayerXValues();
    DeterminePlace();
}

FindAllPlayers的功能是查找所有带有标签“ Player”的对象,并将索引号分配给播放器(稍后它将由播放器插槽对多人游戏进行排序,例如它们是否为player1,player2等)。

public void FindAllPlayers()
{
    if (playerList == null)
    {
        playerList = GameObject.FindGameObjectsWithTag("Player");
        for (int i = 0; i < playerList.Length; i++)
        {
            playerList[i].GetComponent<CharacterStats>().playerNumber = i;
        }
    }
}

FindPlayerXValues的目的是用所有玩家的X位置填充distanceValue数组,并按照它们在playerList数组中的填充顺序进行分配。 (这也使playerList [1] == distanceValue [1]!)

public void FindPlayerXValues()
{
    if (playerList != null)
    {
        distanceValue = new float[] { playerList[0].transform.position.x * -1,
        playerList[1].transform.position.x * -1,
        playerList[2].transform.position.x * -1,
        playerList[3].transform.position.x * -1,
        playerList[4].transform.position.x * -1};
    }
}

然后首先确定字段函数对distanceValue数组进行排序。接下来,它更新位置。

我的计划是,它从链接的playerList数组元素中获取myPosition变量,然后分配排序后链接的distanceValue元素所在位置的索引号。

    public void DeterminePlace()
    {
        Array.Sort(distanceValue);
        for (int i = 0; i < distanceValue.Length; i++)
        {

            playerList[i].GetComponent<CharacterStats>().myPosition = Array.IndexOf(distanceValue, distanceValue[i]); 
        }
    }
}

到目前为止,无论distanceValue元素位于何处,玩家的myPosition变量均保持不变。这就是我期望的那样。

[0]=distanceValue[0] = 1st Place --> [0]=distanceValue[3] = 1st Place
[1]=distanceValue[1] = 2nd Place --> [1]=distanceValue[0] = 2nd Place
[2]=distanceValue[2] = 3rd Place --> [2]=distanceValue[1] = 3rd Place
[3]=distanceValue[3] = 4th Place --> [3]=distanceValue[2] = 4th Place
[4]=distanceValue[4] = 5th Place --> [4]=distanceValue[4] = 5th Place

这似乎是现实...

[0]=distanceValue[0] = 1st Place --> [3]=distanceValue[3] = 4th Place
[1]=distanceValue[1] = 2nd Place --> [0]=distanceValue[0] = 1st Place
[2]=distanceValue[2] = 3rd Place --> [1]=distanceValue[1] = 2nd Place
[3]=distanceValue[3] = 4th Place --> [2]=distanceValue[2] = 3rd Place
[4]=distanceValue[4] = 5th Place --> [4]=distanceValue[4] = 5th Place

我可以在代码中实现什么以使结果更接近第一个结果?

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我怀疑问题出在这行:

playerList[i].GetComponent<CharacterStats>().myPosition = Array.IndexOf(distanceValue, distanceValue[i]);

这是在distanceValue数组中查找同一数组的索引i处的值的索引。...即,总是要返回i。

也许你是说:

playerList[i].GetComponent<CharacterStats>().myPosition = Array.IndexOf(distanceValue, playerList[i].transform.position.x * -1);

对于每个玩家,应该在排序的距离数组中找到他们的X位置,从而找到他们的排名。