我在一个类中有大约20个列表
public class Storepart : MonoBehaviour
{
public List<GameObject> A;
public List<GameObject> B;
}
和我需要保存一个特殊的索引在每个,有办法重构它吗?
public savedata() {
for (int i = 0; i < Storepart.A.Count; i++) {
if (Storepart.A[i].activeSelf) {
SaveAindex = i;
}
}
for (int i = 0; i < Storepart.B.Count; i++) {
if (Storepart.B[i].activeSelf) {
SaveBindex = i;
}
}
}
您可以在这里尝试一个简单的LINQ
方法。
using System.Linq;
SaveAindex = Storepart.A.IndexOf(Storepart.A.LastOrDefault(gameObject => gameObject.activeSelf));
这个表达式由两部分组成。对LastOrDefault
的内部调用遍历列表并返回activeSelf
为真的最后一个元素。外部调用获得LastOrDefault
找到的元素的索引。
备注:
- 如果您正在寻找
List<GameObject
中activeSelf?
为真的第一个元素,请使用FirstOrDefault
- 如果没有找到任何元素,这个LINQ表达式的结果将是0。