- Home /
Binding component with MonoBehaviour so they are added together by inspector's "Add Component".
Hello. I want to bind a MonoBehaviour to a specific component so whenever I add this component in inspector it automatically adds the script to the game object, just like canvas renderer is added whenever you add an image or other UI components. It doesn't have to stick with it, I'm perfectly fine with the possibility of destroying the script while leaving the component or not adding it with the component by AddComponent function. Can I achieve something like that with a custom MonoBehaviour? The specific components I want to bind script with are AudioSource and Text.
Sorry for any mistakes in my English.
Answer by HammerCar · Sep 10, 2017 at 08:36 PM
Just add RequireComponent above the class https://docs.unity3d.com/ScriptReference/RequireComponent.html https://docs.unity3d.com/ScriptReference/RequireComponent-ctor.html
[RequireComponent(typeof(AudioSource), typeof(Text))]
public class ExampleClass : MonoBehaviour
{
}
That would be perfect if I had an access to Text class and AudioSource class because I want to bind the script to them, not the way require component works (if I understand the way it works right). So I add the AudioSource and then my $$anonymous$$onoBehaviour appears, is required or whatever. I will leave the question open for now. Thanks anyway.