0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

UnityECSでGameObjectリストからEntityリストを作成する

Last updated at Posted at 2024-05-09

Unity 6000.0.0f1
Entities 1.2.1

Unity EntityComponentSystem(ECS)勉強中の者です。
間違っていたらすみません。
IComponentDataはそもそもリストや配列は使用できません。
NativeArray<Entity>なら!と思いましたがこれも

ArgumentException: srcEntity is not a valid entity

というエラーでダメでした。
結論、リストや配列のGameObjectをECSで使用するにはDynamicBufferを使用するといいみたいです。

SampleComponentData.cs
//コンポーネントデータ
public struct SampleComponentData : IComponentData { }
//バッファ
public struct SampleElement : IBufferElementData
{
    public Entity sampleEntity;
}
SampleAuth.cs
//オーサリング
public class SampleAuthoring : MonoBehaviour
{
    public List<GameObject> prefabs;
}
public class SampleAuthoringBaker : Baker<SampleAuthoring>
{
    public override void Bake(SampleAuthoring authoring)
    {
        var entity = GetEntity(TransformUsageFlags.Dynamic);
        var sample = new SampleComponentData();
        var buffer = AddBuffer<SampleElement>(entity);
        for (int i = 0; i < authoring.prefabs.Count; i++)
        {
            var prefab = authoring.prefabs[i];
            buffer.Add(new SampleElement
            {
                sampleEntity = GetEntity(prefab, TransformUsageFlags.Dynamic)
            });
        }
        AddComponent(entity, sample);
    }
}

使用例

SampleSystem.cs
//システム
public partial struct SampleSystem : ISystem
{
    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        foreach (var buffer in SystemAPI.Query<DynamicBuffer<SampleElement>>().WithAll<SampleComponentData>())
        {
            for (int i = 0; i < buffer.Length; i++)
            {
                var entity = buffer[i].sampleEntity;
                state.EntityManager.Instantiate(entity);
            }
        }
        state.Enabled = false;
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?