Custom inspector adding scripts

Heya,

I was wondering, I have a game object in a scene which allows me to define via booleans in the inspector which game modes are available for the current scene.
In order to define all attributes for the game objects which are childs of the former mentioned game object I would like to attach scripts to each child based on which game modes have been selected.

E.g.:

  • GameObject Parent has booleans active for (exploreMode and PuzzleMode)
  • All children of “Parent” should now automatically get the scripts for exploreMode and PuzzleMode attached.

Is this possible in Unity ? I assume it needs to be done via a Custom inspector?! Any hints / help is welcomed.

I’m not sure if I understood your need correctly but If you are making custom editor / inspector and want to add components via there (for dev purposes) then use

UnityEditor.Undo.AddComponent<ComponentTypeYouWantToAttach>(gameObject_reference);

If you need (and probably will) also to remove components then use

UnityEditor.Undo.DestroyObjectImmediate(ComponentReferenceYouWantToRemove)

If you need instructions how to make the custom inspector for you “selector” script then check it here:

I advice not to continuously check the boolean values + adding components in OnInspectorGUI() but to add button click to check them and make changes based on the boolean values. Like this:

public override void OnInspectorGUI()
{
       if (GUILayout.Button("Add Components"))
        {
            //check booean values and add (and maybe remove also) components based on them...
        }
       DrawDefaultInspector();
}

On the other hand if you want this Component adding to happen when the game is started then you can add the components in the Start(). There you dont need any customer editors. Just use gameObject_reference.AddComponent<ComponentType>()..