How do I hold a reference to an Entity on a component?

I want to attach components to entities at runtime but to do this I want to hold a reference to an entity as part of a system so I can easily tell it to add a component.

With game objects this is simple, I’d add a public game object field to the component and then wire up the reference in the editor. This doesn’t work in ECS because entities are created at runtime.

So really my question is, assuming that my system has a public Entity variable, how do I set it to the Entity I want to reference and where do I do this from?

Thanks!

** I realized after I posted that the question in the title should be How do I hold a reference to an Entity in a system (and not Component)

You shouldn’t have a reference to an entity on your system but rather have a component in another entity that hold that.
Maybe a Singleton can apply here depending on what you need.
You can look at how the conversion workflow works here to reference other entities from gameObjects, but take a look at this specifically.

This definitely seems what I’m looking for BUT, I can’t seem to get it to work. The reference it’s storing is an Entity at index 3 with 0 components. The prefab in the scene is converted to an Entity with index 0, with the correct components. Not sure why there’s a mismatch. There’s no link between Entity with index 0 and my component.

My code is 1:1 with the sample, except for the fact that I’m not instantiating the prefab in the system, but rather I’m referencing a GO (which is a prefab) in the scene.

I think I got it! Was missing an interface “IDeclareReferencedPrefabs”

1 Like