How to reference prefab from within a system

When spawning a bunch of new entities i would like to also give them a prefab graphic. This graphic would always be the same and never change. Ideally i would like to have a reference to this prefab such as

Using Unity.Entities;

public class Spawner: SystemBase
{
    Prefab prefab = prefab that already exists.
    protected override void OnUpdate()
    {
     // spawn entities with prefab
    }
}

However i cannot figure out how to do this. The way i think i can do it is instead to create a unique entity in the editor with a unique component that has a reference to this prefab. I would then use a .foreach or entity query to retrieve this data and never use that entity again. To me this unnecessary as i would rather just directly get the prefab without an inbetween. Is something like that possible or how am i supposed to do it?

As simple solution - place your prefab into Resources folder and load it in OnCreate method of your system.

1 Like

One possibility would be to use a MonoBehaviour. In the start method you convert the prefab into an entity prefab and then inject it to the system.

That really is a simple solution and i will probably end up using it thanks! I did a small bit of reading on the resources folder is seems the general consensus is to avoid using it if possible. I probably still will use it as i doubt its going to cause problems with just a few uses. But i wonder what is the more ECS/DOTS way of referencing the prefab in a system?

The other way is to put the prefab and other data like how often to spawn on an entity with an authoring component etc and then ForEach over those entities in OnUpdate. That way the same system can be used for spawning multiple things.

If you really only have one, you can use singleton entities instead and maybe cache the prefab data in OnCreate but the idea would be the same.