重构大列表

发布于 2025-02-06 20:50:21 字数 529 浏览 0 评论 0原文

我在下面的课程中大约有二十个列表

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;
        }
    }
}

I HAVE About twenty lists in a class like below

public class Storepart : MonoBehaviour
{
    public List<GameObject> A;

    public List<GameObject> B;
}

and I need to save a special index in each one, is there a way to refactor it?

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;
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

坐在坟头思考人生 2025-02-13 20:50:21

您可以在此处尝试简单的linq ablect。

using System.Linq;

SaveAindex = Storepart.A.IndexOf(Storepart.A.LastOrDefault(gameObject => gameObject.activeSelf));

此表达式由2个部分组成。内部调用lastOrdOdefault遍历您的列表,并返回ActiveSelf为true的最后一个元素。外部呼叫获取lastOdordEfault找到元素的索引。

备注:

  • 如果您正在寻找list&lt; gameObject white activiveSelf? true使用firstordordefault
  • 该LINQ Expresion的结果将会如果找不到元素,则为0。

You can try a simple LINQ aproach here.

using System.Linq;

SaveAindex = Storepart.A.IndexOf(Storepart.A.LastOrDefault(gameObject => gameObject.activeSelf));

This expression consists of 2 parts. The inner call to LastOrDefault traverses your List and returns the last element where the activeSelf is true. The outer call gets the index of the element found by LastOrDefault.

Remarks:

  • If you are looking for the first element in your List<GameObject where activeSelf? is true use FirstOrDefault
  • The result of this LINQ expresion will be 0 if no element is found.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文