Unity GameObject,其中包含包含其他对象的列表

时间:2017-02-01 09:07:24

标签: c# unity3d

对于我在Unity工作的学校项目。我正在做一个游戏"您需要使用电缆连接设备的地方。 所以我有一个名为" device"使用脚本" deviceController"。 Device对象有一个List,其中包含一个名为" portController"的脚本的其他对象。 目前我试图在deviceController中将bool(anyCablesConnected)设置为true,如果设备的端口中有任何电缆,并且如果没有连接到设备的电缆,则将bool设置为false。 portController还有一个名为" Occupied"。

的bool

只有我不知道该怎么做。我是否使用foreach循环或类似的东西?

foreach(port in device){
   // IF A PORT FROM A DEVICE IS OCCUPIED, SET ANYCABLESCONNECTED TO TRUE
   if (occupied == true){
       anyCablesConnected = true;
   } else {
       anyCablesConnected = false;
   }
}

这样的东西?我还没有真正使用foreach循环。但我希望你们能帮助我!

2 个答案:

答案 0 :(得分:1)

如果我理解正确,如果连接了至少一根电缆,anyCablesConnected应该是真的。其逻辑是:

anyCablesConnected = false;

foreach (var port in device)
{
    // IF A PORT FROM A DEVICE IS OCCUPIED, SET ANYCABLESCONNECTED TO TRUE
    if (port.GetComponent<portController>().occupied)
    {
        anyCablesConnected = true;

        // No need to continue looping, we have already found a cable
        break;
    }
}

或者您可以使用LINQ获得更紧凑的解决方案:

anyCablesConnected = device.Any(x => x.GetComponent<portController>().occupied);

请注意,我已经对如何访问occupied标志做了一些假设!

答案 1 :(得分:0)

好吧,虽然写答案似乎已经出现了。但是为了让我能够删除所有内容,同时为您提供有关foreach如何运作的背景信息。

包含字符串的列表; List<string>,将写成:

List<string> listWithStrings = new List<string>();

listWithStrings.Add("Hello");
listWithStrings.Add("World");

与foreach一起循环:

foreach (string stringInList in listWithStrings) {
    Debug.Log(stringInList); 
    // The first loop stringInList will be "Hello", 
    // the second loop it will be "World"
}

这与标准for-loop几乎相同:

for (int i = 0; i < listWithStrings.Count; i++) {
    Debug.Log(listWithStrings[i]);
}

但是更轻松,更清洁。

相关问题