I've seen a few places where Unity has the ability to "link" or otherwise require component dependencies that are added (at edit-time) and cannot be removed until the dependent component itself is removed.
Is there a way to use this behavior from custom scripts?
I know that you can create components at runtime using ObjectFactory, but it's expensive and doesn't solve the problem of being able to tweak parameters on the dependency components manually.
Yes - the [RequireComponent(typeof(SomeDependencyComponent))] attribute does exactly this.
For example:
[RequireComponent(typeof(AudioSync))]
public class BehaviorPlayer : MonoBehaviour
{
private AudioSync audioSync;
public void Start() {
audioSync = GetComponent<AudioSync>();
}
}
This automatically creates an AudioSync component (in this case, a custom script in my project) that is guaranteed to be present
at runtime, barring any programmatic removals.
It also shows up as an editor component on the game object that can be manually tweaked:
Further, if I try to remove the required AudioSync component, Unity spits out an error: