繁体   English   中英

如何在Unity C#中拆分共享对同一类的引用的对象列表

[英]How do I split a list of objects that share a reference to the same class in Unity C#

我想按特定条件拆分对象列表。

标准是对象共享对同一类的引用。

到目前为止,这就是我所拥有的。 我有一个基础课

public class Enemy : MonoBehaviour
{  
}

和那个班级的孩子

public class Snake : Enemy
{
    public List<snakePart> SnakeParts; 

    // A list of Snake Parts that this class creates and modifys
    // other general snake stuff like hissing etc etc
}

snakePart类主要用于存储数据。 它还使用BoxColliders和游戏中的东西创建GameObjects。

public class snakePart : ScriptableObject
{
    private Color snakeColor;
    private int arrayIndex;
    private Snake snakeParent;

    // Create a new game object

    private GameObject createNewGameObject(int _arrayIndex, Snake _Snake)
    {
        GameObject newGameObject = // new game object stuff
        newGameObject.AddComponent<EnemyIdentifier>().identifierInit(_arrayIndex, _Snake);
        return newGameObject ;
    }
}

它将EnemyIdentifier脚本附加到它制作的游戏对象上。 目的是告诉我谁拥有这个特定的游戏对象。

public class EnemyIdentifier: MonoBehaviour
{
    public void identifierInit(int _arrayIndex, Enemy _owner)
    {
        ArrayIndex = _arrayIndex;
        Owner = _owner;
    }

    public int ArrayIndex;
    public Enemy Owner;
}

我在游戏中有几个这些snakeParts ...最终我可能还会有狗部分,狼部分等。我解雇了一些东西,这些东西聚集了一大堆RayCastHit2D,并将它们变成了对这些EnemyIdentifers的大量引用。

List<EnemyIdentifier> EnemyIdentitys = new List<EnemyIdentifier>();



       foreach (RaycastHit2D hit in enemyHits)
        {
            EnemyIdentitys.Add(hit.transform.GetComponent<EnemyIdentifier>());
        }

我想知道的是, 如何在“ EnemyIdentitys”列表中挑选出引用相同“所有者”的任何内容。

将它们添加到自己的列表中。

重复此过程,直到所有EnemyIdentity都基于它们是否共享所有者而在自己的列表中。

非常感谢您抽出宝贵时间来查看我的问题,并预先感谢您可能提出的任何建议或代码提示。

在Agapwlesu的帮助下,我决定使用Linq。

这是解决方案

        if (enemyHits.Length > 0)
        {
            List<EnemyIdentifier> EnemyIdentitys = new List<EnemyIdentifier>();
            foreach (RaycastHit2D hit in enemyHits)
            {
                EnemyIdentitys.Add(hit.transform.GetComponent<EnemyIdentifier>());
            }
            var groupedEnemyIdentitys = EnemyIdentitys
                .GroupBy(x => x.Owner)
                .Select(grp => grp.ToList())
                .ToList();
        }

您可以通过以下方式获取列表的子集:

EnemyIdentitys.Where(x=>x.Owner == thisOwner);

要么

EnemyIdentitys.GroupBy(x.Owner)

应该给您一个列表集合,每个列表都有不同的所有者。 它使用LINQ,因此您需要包括它:

using System.Linq;

如果不使用Linq,则必须创建自己的代码,将列表划分为子列表。 在这种情况下,最好先将数据存储在不同的结构中。 如果您有一个所有者列表,请向每个所有者添加他们拥有的EnemyIdentity。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM