首页 > 解决方案 > 使用 Array.Sort 仅对元素进行排序而不对索引号进行排序?

问题描述

首先快速浏览一下我的代码..

这里我有两个数组,一个游戏对象和一个浮点数组..

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

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

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

FindAllPlayers 的功能是查找所有带有“玩家”标签的对象,并将索引号分配给玩家(稍后它将由多人游戏的玩家插槽排序,例如他们是 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};
    }
}

而DeterminePlace函数首先对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

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

提前感谢您的帮助!

标签: c#arrayssortingunity3dindexof

解决方案


我怀疑问题出在这一行:

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 位置,从而找到他们的排名。


推荐阅读