Hello!
I am trying to get started with Unity ECS and run into difficulties checking if an IAspect has an optional component. As far as I can tell I am supposed to use “_myOptionalComponent.IsValid” within the aspect struct to check if the component exists, however, even if I am fairly sure that the component should exist .IsValid always returns “False”.
Consider this simple system:
Components:
using Unity.Entities;
namespace Test
{
public struct TestValueComponent : IComponentData
{
public int ValueWithTag;
public int ValueWithoutTag;
}
public struct TestTag : IComponentData { }
}
Authoring + Baking:
using Unity.Entities;
using UnityEngine;
namespace Test
{
public class TestAuthoring : MonoBehaviour
{
public bool AddTestTag;
}
public class TestBaker : Baker<TestAuthoring>
{
public override void Bake(TestAuthoring authoring)
{
if (authoring.AddTestTag)
{
AddComponent<TestTag>();
}
AddComponent(new TestValueComponent
{
ValueWithTag = 0,
ValueWithoutTag= 1
});
}
}
}
}
Aspect:
using Unity.Entities;
namespace Test
{
public readonly partial struct TestAspect : IAspect
{
private readonly RefRO<TestValueComponent> _testComponent;
// I think the problem is somewhere around here?
[Optional] private readonly RefRO<TestTag> _testTag;
public bool HasTag() => _testTag.IsValid;
public int GetValueWithTag() => _testComponent.ValueRO.ValueWithTag;
public int GetValueWithoutTag() => _testComponent.ValueRO.ValueWithoutTag;
}
}
System + Job:
using Unity.Burst;
using Unity.Entities;
namespace Test
{
[BurstCompile]
public partial struct TestSystem : ISystem
{
[BurstCompile]
public void OnCreate(ref SystemState state) { }
[BurstCompile]
public void OnDestroy(ref SystemState state) { }
[BurstCompile]
public void OnUpdate(ref SystemState state)
{
new TestJob
{
}.ScheduleParallel();
}
}
[BurstCompile]
public partial struct TestJob : IJobEntity
{
[BurstCompile]
private void Execute(ref TestAspect aspect)
{
if (aspect.HasTag())
{
UnityEngine.Debug.Log(aspect.GetValueWithTag().ToString());
}
else
{
UnityEngine.Debug.Log(aspect.GetValueWithoutTag().ToString());
}
}
}
}
Then I create a new GameObject within an empty subscene and add the TestAuthoring script. Now, from what I understand, the moment I enter player I should get a lot of "0"s in the console when I have checked the “AddTestTag” checkbox on the TestAuthoring Gameobject and “1” if I didnt. However, in both cases, I only get "1"s, i.e. the aspect doesnt find the optional component even if the Inspector tells me that it is attached to the entity.
I am fairly sure that I am overlooking something really obvious here, but as it stands I am at my wit’s end. Thanks in advance for your help!