Automatically add script to created UI items

I am looking to enable Unity to automatically add a script to created UI objects, instantiated through the GameObject > UI menu.

I want to apply a script to the following elements when created.

  • Button
  • Toggle
  • Slider
  • Scrollbar

Essentially any intractable element.

I am guessing Unity adds the components to the gameobject on creation, as they do not have the (clone) suffix.

To prevent this from being too inconvenient, I was wondering if this could be controlled by a boolean in an editor window.

You can do it through editor scripting. Either as a check when something is added, or add variations of the existing components as menu options.

Alternatively, if it is the same script, you could just make a script that adds the script, and bind it to a key stroke. So you would select the element and hit the key.

On the first one idea, how would I create menu variations for these without instantiating prefabs?
I would prefer this to be minimalistic, so I don’t need a prefab folder to keep them in.

So, for example, I would have a menu item called Button 2 (or anything else) and that would create a button exactly the same way the original Button menu item would, but also adds a script to it.

You would basically create a new GameObject and add the additional components via the additional params. So in the simplest form would be something like this:

using UnityEngine;
using UnityEditor;
using UnityEngine.UI;
using System.Collections;

public class AddButtonAlt : ScriptableObject {

    [MenuItem("GameObject/UI/AltButton")]
    static void InsertMyButton()
    {
        GameObject button = new GameObject ("AltButton", typeof(CanvasRenderer), typeof(Image), typeof(Button), typeof(MyButtonScript)) as GameObject;
    }
   
    [MenuItem("GameObject/UI/AltImage")]
    static void InsertMyImage()
    {
        GameObject image = new GameObject ("AltImage", typeof(CanvasRenderer), typeof(Image), typeof(MyButtonScript)) as GameObject;
    }

}

The “MyButtonScript” would be your script. This is will just add it to the hierarchy, it won’t nest it like the normal add, but that with a little work, that can be added, by checking what is selected and adding it there.