Managed components
Unlike unmanaged components, managed components can store properties of any type. However, they're more resource intensive to store and access, and have the following restrictions:
- You can't access them in jobs.
- You can't use them in Burst compiled code.
- They require garbage collection.
- They must include a constructor with no parameters for serialization purposes.
Managed type properties
If a property in a managed component uses a managed type, you might need to manually add the ability to clone, compare, and serialize the property.
Create a managed component
To create a managed component, create a class that inherits from IComponentData and either has no constructor, or includes a parameterless constructor.
The following code sample shows a managed component:
// Declare a class to create a managed component
public class ExampleManagedComponent : IComponentData
{
public int Value;
}
Manage the lifecycle of external resources
If a managed component references an external resource, you can implement the ICloneable and IDisposable interfaces to link that resource's lifecycle to the entity:
- Unity calls
Clone()when it duplicates the managed component, for example, when you instantiate the entity. ImplementICloneableto give the new component its own copy of the resource instead of sharing the original. - Unity calls
Dispose()when it removes or replaces the managed component, or destroys the entity. ImplementIDisposableto release the resource.
Unity also copies and disposes managed components internally. Implementing ICloneable ensures each copy owns its own resource.
Optimize managed components
Unlike unmanaged components, Unity doesn't store managed components directly in chunks. Instead, Unity stores them in one big array for the whole World. Chunks then store the array indices of the relevant managed components. This means when you access a managed component of an entity, Unity processes an extra index lookup. This makes managed components less optimal than unmanaged components.
The performance implications of managed components mean that you should use unmanaged components instead where possible.