我正在关注此演讲https://www.youtube.com/watch?v=BNMrevfB6Q0并尝试了解如何在单击鼠标时生成单位(用于测试目的)。
一般来说,我创建了一个 UnitBase 等,它实现了 IConvertGameObjectToEntity::Convert 以确保所有单位都可以转换为实体对象,如下所示:
namespace Units
{
public abstract class UnitBase : MonoBehaviour, IConvertGameObjectToEntity
{
public float health;
public bool selected;
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
dstManager.AddComponentData(entity, new Translation {Value = transform.position});
dstManager.AddComponentData(entity, new Rotation {Value = transform.rotation});
dstManager.AddComponentData(entity, new Selected {Value = selected});
dstManager.AddComponentData(entity, new Health {Value = health});
}
}
public abstract class MobileUnitBase : UnitBase
{
public float speed;
public new void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem)
{
base.Convert(entity, dstManager, conversionSystem);
dstManager.AddComponentData(entity, new Speed {Value = speed});
}
}
}
这些是主要组件:
namespace ECS.Components
{
public class Health : IComponentData
{
public float Value;
}
public class Speed : IComponentData
{
public float Value;
}
public class Selected : IComponentData
{
public bool Value;
}
}
现在,在我的测试脚本中,我有这个:
public class Test : MonoBehaviour
{
public GameObject unitPrefab;
private EntityManager _entityManager;
private Entity _unitEntityPrefab;
// Start is called before the first frame update
void Start()
{
_entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
_unitEntityPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(unitPrefab, World.Active);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
SpawnUnit(15, 15);
}
}
private void SpawnUnit(float x, float z)
{
Debug.Log($"Spawning unit at x:{x} y:{z}");
var unitEntity = this._entityManager.Instantiate(this._unitEntityPrefab);
_entityManager.SetComponentData(unitEntity, new Translation {Value = new Vector3(x, 1, z)});
_entityManager.SetComponentData(unitEntity, new Rotation {Value = Quaternion.Euler(0, 0, 0)});
_entityManager.SetComponentData(unitEntity, new Health {Value = 100f});
_entityManager.SetComponentData(unitEntity, new Selected {Value = false});
}
}
其中 unitPrefab 只是一个简单的 GameObject,上面有一个 Capsule 和一个基本上是空的脚本,现在是空的:
public class UnitScript : UnitBase
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
问题是,当我单击时,实体被创建但单元没有被渲染。
显然我错过了一些东西,但我不明白它是什么。
任何帮助将非常感激!