Fetching Managed components from System always returns Null

I’m trying to reference a few managed components such as Animator and AudioSource on the system that handles movement but regardless of which method I use:

SystemAPI.ManagedAPI.GetComponent<Animator>(entity);
// or
this.EntityManager.GetComponentObject<Animator>(entity);

It returns Null and I’m unable to utilize them.

I add these components during the baking process like so:

var entity = this.GetEntity(TransformUsageFlags.Dynamic);
this.AddComponentObject(entity, authoring.GetComponent<AudioSource>());
this.AddComponentObject(entity, authoring.GetComponent<Animator>());

They are both enabled on the prefab that is spawned into the scene. Any help is appreciated!

Both a baked scene entity and a baked prefab seem to work just fine in Entities 1.2.1 on editor 6000.0.3f1.

Which entities / editor version are you using?

Are you absolutely sure you’re querying on the right entity?

Do you see the component when inspecting the loaded Entity?
9855285--1419216--upload_2024-5-25_17-36-56.png

Try this on a new scene with an object (or prefab that gets spawned) that has ExpAuthoring and AudioSource, does the AudioSource show up and get logged?

using Unity.Entities;
using UnityEngine;

public class ExpAuthoring : MonoBehaviour
{
    public int tagValue;
}

public struct Exp : IComponentData
{
    public int Tag;
}

public class ExpBaker : Baker<ExpAuthoring>
{
    public override void Bake(ExpAuthoring authoring)
    {
        Entity e = GetEntity(TransformUsageFlags.Dynamic);
        AddComponent(e, new Exp { Tag = authoring.tagValue });
        AddComponentObject(e, authoring.GetComponent<AudioSource>());
    }
}

public partial struct ExpSystem : ISystem
{
    public void OnUpdate(ref SystemState state)
    {
        foreach ((Exp exp, Entity entity) in SystemAPI.Query<Exp>().WithEntityAccess())
        {
            Debug.Log($"{entity} ({exp.Tag}): {SystemAPI.ManagedAPI.GetComponent<AudioSource>(entity)} // {state.EntityManager.GetComponentObject<AudioSource>(entity)}");
        }
    }
}

I see the categories ‘AudioSource’ and ‘Animator’ on the entity at runtime but it seems that they don’t have a value assigned. See screenshot:

The prefab that has the authoring script has the components active and enabled so not sure why it isn’t adding them to the entity properly. I also debugged to check during the baking process and authoring.GetComponent<Animator>() is not null so not sure what I could be missing here

Edit: This is what my system looks like

using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
using Unity.Transforms;
using UnityEngine;

[UpdateInGroup(typeof(PredictedSimulationSystemGroup))]
public partial class PlayerMovementSystem : SystemBase {
    protected override void OnUpdate() {
        var speed = SystemAPI.Time.DeltaTime * 4;
        foreach(var (input, mouseInput, localTransform, entity) in
            SystemAPI.Query<RefRO<PlayerMovementInput>, RefRW<PlayerMouseInput>, RefRW<LocalTransform>>().WithEntityAccess()
            .WithAll<GhostOwnerIsLocal>()
            .WithAll<Simulate>()) {
            var animator = SystemAPI.ManagedAPI.GetComponent<Animator>(entity); //this.EntityManager.GetComponentObject<Animator>(entity);
            if(animator != null) {
                animator.Play("Standing");
            }

            // update player look rotation before calculating movement
            mouseInput.ValueRW.MouseX *= SystemAPI.Time.DeltaTime;
            mouseInput.ValueRW.MouseY *= SystemAPI.Time.DeltaTime;
            localTransform.ValueRW.Rotation = math.nlerp(localTransform.ValueRO.Rotation,
              math.mul(localTransform.ValueRO.Rotation, quaternion.Euler(0f, mouseInput.ValueRO.MouseX, 0f)),
                1f);

            var moveInput = new float2(input.ValueRO.Horizontal, input.ValueRO.Vertical);
            moveInput = math.normalizesafe(moveInput) * speed;
            float3 movement = localTransform.ValueRO.Right() * moveInput.x + localTransform.ValueRO.Forward() * moveInput.y;

            localTransform.ValueRW.Position += movement;
        }
    }
}

I am using Entities 1.2.1 (Netcode) and 2022.3.27f1

Okay I’m not sure what I changed but the values are showing up now :face_with_spiral_eyes:

However it still complains that they are inactive:
Warning: Game object with animator is inactive
UnityEngine.Animator.Play (string)

This is strange, now I do not see the Animator component at all anymore at runtime, I am getting an error though that seems to be pointing me to the fact that there is some entity baking issue:

InvalidOperationException: Baking error: Attempt to add duplicate component UnityEngine.AudioSource for Baker PlayerManagedComponentBaking with authoring component PlayerManagedComponentAuthoring. Previous component added by Baker Unity.Rendering.AudioSourceCompanionBaker. GameObject 'FPSGenericPlayerEntity', baked in World 'Converted Scene: 'SharedData''.

I figured that this might be because I had my Baking classes within the Authoring components but even after moving them out and declaring them public it is giving me the same error.

I’m not sure where Unity.Rendering.AudioSourceCompanionBaker is coming from though (which is what is supposedly adding the other Animator) or why I still see Audio Source on the entity but not Animator…

I tried enabling domain reloading thinking it was a caching issue but that didn’t help, also I don’t have any other MonoBehaviours attached to the prefab other than the authoring ones for the managed components:

using Unity.Entities;
using UnityEngine;

[DisallowMultipleComponent]
[RequireComponent(typeof(AudioSource))]
[RequireComponent(typeof(Animator))]
public class PlayerManagedComponentAuthoring : MonoBehaviour { }

public class PlayerManagedComponentBaking : Baker<PlayerManagedComponentAuthoring> {
    public override void Bake(PlayerManagedComponentAuthoring authoring) {
        var entity = this.GetEntity(TransformUsageFlags.Dynamic);
        this.AddComponentObject(entity, authoring.GetComponent<AudioSource>());
        this.AddComponentObject(entity, authoring.GetComponent<Animator>());
    }
}

Turns out this is a thing that gets added with Entities Graphics (sort of seems out of place…)
https://github.com/needle-mirror/com.unity.entities.graphics/blob/9ab5adea7d464c55258ee3cf405d4ab5fe3ad71e/Unity.Entities.Graphics/EntitiesGraphicsConversion.cs#L101
Getting an exception thrown for adding the AudioSource would then prevent the code from continuing to add the Animator.
In this case, you would want to avoid using a baker to add AudioSource, and instead rely on the RequireComponent attribute as you are now.

1 Like

Ah I see, I removed manually baking the AudioSource component and now they are both consistently appearing in the entity at runtime. Now to figure out why the animator is inactive, I’ll keep tinkering around, thanks for the help!