我目前正在Unity中进行一个小型项目,以测试一些新功能,主要是new Input System,而且我在将列表包围时有些麻烦。我在这个项目中的目标是制作一个脚本,为每个玩家创建一个小光标,以供他们使用并使用各自的控制器进行移动。
当前,每当我的计算机检测到新的Gamepad Controller时,我就会在列表中创建和存储对象。我遇到的问题是找到一种方法来删除不在列表内的多余对象,即当列表尺寸减小时(在这种情况下是玩家断开其Gamepad Controller的连接时)。
在过去的项目中,每当我不得不尝试从列表中删除项目时,我都曾遇到过类似的问题。
我试图在这样的答案中寻找答案,以试图在多个网站(包括该网站)上实现这种效果,但没有成功。
这是我当前使用的代码,每当添加新设备时,我就使用它们来添加播放器。
public GameObject cursorPrefab;
public int amountOfPlayers = 4;
List<GameObject> currentPlayers = new List<GameObject>();
private void DynamicADP(){
if(Gamepad.all.Count > amountOfPlayers) return;
for(int i = 0; i < Gamepad.all.Count; i++){
if(currentPlayers[i] != null) continue;
Cursor obj = Instantiate(cursorPrefab).GetComponent<Cursor>();
obj.PlayerDevice = Gamepad.all[i];
currentPlayer.Add(obj.gameObject);
}
}
编辑:虽然Kevins解决方案不能完全解决问题,但是它确实帮助我拓宽了对这一问题的看法,最终使我可以用这段代码解决我想要的问题!所以我会接受凯文的回答!谢谢凯文!
这是我添加的内容,非常简单。
private void DynamicADP(){
//Previous logic from the code snipper above
if(currentPlayers.Count > Gamepad.all.Count){
Destroy(currentPlayers.Count[currentPlayers.Count - 1]);
currentPlayers.RemoveAt(currentPlayers.Count - 1);
//Whenever there is a difference in size on both lists, remove the last
//object from both in-scene and from currentPlayers list.
}
}
}
答案 0 :(得分:2)
反向循环以从列表中删除项目。
private void DynamicADP(){
if(Gamepad.all.Count > amountOfPlayers) return;
for(int i = Gamepad.all.Count-1; i >=0 ; i--){
if (somelogic) Gamepad.all.RemoveAt(i);
}
}
答案 1 :(得分:0)
List不是UnityEngine类,如果您统一寻求List方法,您将永远找不到。但是您可以在Microsft API文档中。
我从没在Unity中使用过list,但是我认为这种方式应该可行:
currentPlayers.RemoveAt(removed_controller_index);
在Microsft文档上查看更多列表: https://docs.microsoft.com/pt-br/dotnet/api/system.collections.generic.list-1?view=netframework-4.7.2