c# - 使用 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
我可以在我的代码中实现什么以更接近第一个结果?
提前感谢您的帮助!
解决方案
我怀疑问题出在这一行:
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 位置,从而找到他们的排名。
推荐阅读
- database - Laravel 从带有哈希的表单更新用户密码
- javascript - styled-components 基于 props 来回动画
- c# - “this”这个词是什么意思,“static”是什么意思?
- php - 允许上传原始文件名
- c# - 在 int List 中插入值然后对列表进行排序的最快方法
- python-3.x - Watson-NLU 在循环中给出下游问题(500),但不是单独在句子上
- javascript - 检测可编辑 div 中动态创建的跨度上的退格键
- android - 如何更改后台运行的应用程序图标?
- javascript - Javascript从url打开txt并输出为HTML
- android - 使用 google smart lock 进行 oauth 登录方法