在 Unity 中,可以使用 List 的 FindIndex 方法来检测一个元素是 List 中的第几个元素。下面是一个示例代码:\n\nc#\nusing System.Collections.Generic;\n\nList<int> myList = new List<int>() { 1, 2, 3, 4, 5 };\nint elementToFind = 3;\n\nint index = myList.FindIndex(item => item == elementToFind);\nif (index != -1)\n{\n Debug.Log("Element found at index: " + index);\n}\nelse\n{\n Debug.Log("Element not found in the list.");\n}\n\n\n在上面的代码中,我们首先创建了一个 List 对象并初始化了一些整数值。然后,我们定义了一个要查找的元素 elementToFind,这里是 3。接下来,我们使用 List 的 FindIndex 方法来查找该元素在 List 中的索引。FindIndex 方法接受一个 Predicate 委托作为参数,该委托用于指定要查找的条件。在这个例子中,我们使用了一个 Lambda 表达式作为 Predicate,它检查 List 中的每个元素是否等于要查找的元素。\n\n如果找到了元素,FindIndex 方法将返回该元素的索引。如果找不到元素,FindIndex 方法将返回 -1。在代码中,我们使用一个 if-else 语句来判断元素是否被找到,并打印相应的消息。\n\n请注意,前提是你已经在代码中引入了 UnityEngine 命名空间,以便使用 Debug 类中的 Log 方法来进行调试输出。

Unity List 查找元素索引 - FindIndex 方法代码示例

原文地址: https://www.cveoy.top/t/topic/pPnP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录