目录

Unity-Dots从入门到精通之-Prefab引用-转-实体引用

Unity Dots从入门到精通之 Prefab引用 转 实体引用

前言

DOTS(面向数据的技术堆栈)是一套由 Unity 提供支持的技术,用于提供高性能游戏开发解决方案,特别适合需要处理大量数据的游戏,例如大型开放世界游戏。

本文讲解我在开发Dots的过程中,当我们有一些预制体,希望作为实体,在运行时会克隆出来的,比如士兵和子弹。我们可以新建一个EntitiesReferences实体引用类。用来存储多个预制体转化的实体引用。

  • Unity 2022.3.52f1
  • Entities 1.3.10

安装 DOTS 包

要安装 DOTS 包,请按照以下步骤操作:

(1)从菜单“窗口 → 包管理器”打开包管理器。

(2)搜索“ Entities” 并安装 Entities和Entities Graphics。

(3)搜索“ Universal RP” 并安装 Universal RP,并设置Graphics/Scriptable Render Pipeline Settings。

这会添加“实体”作为依赖项,并递归添加它所依赖的关联包( Burst、Collections、Jobs、Mathematics等)。

https://i-blog.csdnimg.cn/direct/2a076017e0c04b73a80fd45c8a7931c5.png

实体引用Authoring

using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;

public class EntitiesReferencesAuthoring : MonoBehaviour
{
    public GameObject redSoldierPrefab;
    public GameObject blueSoldierPrefab;
    
    public GameObject bulletPrefabPrefab;
    
    public Transform redStartPoint;
    public Transform blueStartPoint;

	//Baker类,把Mono转为Entity
    private class Baker : Baker<EntitiesReferencesAuthoring>
    {
        public override void Bake(EntitiesReferencesAuthoring authoring)
        {
            Entity entity = GetEntity(TransformUsageFlags.Dynamic);
            AddComponent(entity, new EntitiesReferences
            {
                redMeleePrefabEntity = GetEntity(authoring.redSoldierPrefab, TransformUsageFlags.Dynamic),
                blueMeleePrefabEntity = GetEntity(authoring.blueSoldierPrefab, TransformUsageFlags.Dynamic),
               
                bulletPrefabEntity = GetEntity(authoring.bulletPrefabPrefab, TransformUsageFlags.Dynamic),
                
                redStartPosition = authoring.redStartPoint.position,
                blueStartPosition = authoring.blueStartPoint.position,
            });
        }
    }
}

//实体引用类
public struct EntitiesReferences : IComponentData
{
    public Entity redMeleePrefabEntity;
    public Entity blueMeleePrefabEntity;

    public Entity bulletPrefabEntity;
    
    public float3 redStartPosition;
    public float3 blueStartPosition;
}