Add Custom Script Input to Game Object through Script (Custom Editor)

Hi, so I’ve been making a custom editor in Unity and was wondering if there was a way to add a script that’s inputted by the user to a new game object.

using UnityEngine;
using UnityEditor;

public class Namespace : EditorWindow
{
    GameObject obj;
    MonoScript objScript;

    void OnGUI()
    {
        obj = GameObject.CreatePrimitive(PrimitiveType.Cube);
        obj.AddComponent<objScript>();
    }
}

This isn’t my exact code but it’s the part that’s relevant. I’ve tried different things for line 12 but there’s always some error.

OnGUI is executed every single frame, actually more than once per frame.

That means every second you’re making between 60 and 180 cube primitives, so I doubt that will be useful.

Now what exactly are you trying to do, make a button that adds a Component to the selected GameObject? Make a new cube? It’s unclear what your intent is from the above code.

I already have a button to spawn in the cube, but I need it to add the script from the variable objScript to the object. However, line 12 does not work because it’s not a component type, it’s a MonoScript variable, so I’m wondering how to add a custom script/component to a GameObject.

I hope this clarifies.

Never heard of a MonoScript until today. Looking at the docs,

Tells me it is derived from a TextAsset. That means it is intended to map to something on disk, generally speaking.

My spidey sense tells me that if you follow the rules for producing a TextAsset in code (google it up, I certainly don’t remember such things), and instead produce a MonoScript object, it might just get you where you need.

I’m unsure what you mean by that? I also have another piece of code that uses MonoScript but I’m not sure it’s related.

EditorGUILayout.BeginHorizontal();
objExtraScript = EditorGUILayout.Toggle(tab + "Add Custom Script", objExtraScript);
if (objExtraScript) { objExtraComponenet = EditorGUILayout.ObjectField(objExtraComponenet, typeof(MonoScript), false) as MonoScript; }
EditorGUILayout.EndHorizontal();

The problem I’m having is that I need to add a script from a variable to a game object but in the AddComponent function, it only allows you to input the premade components. Maybe it should be MonoBehaviour instead of MonoScript? I don’t know. Thanks for your help btw.

The problem you’re having is more analogous to trying to add a TextAsset to a GameObject.

It can’t be done.

You can create a TextAsset on disk.

You CANNOT add a TextAsset to a GameObject.

You can drag a TextAsset into a public TextAsset field in a Monobehavior.

Based entirely on observing the documentation I quoted above, I speculate that the same goes for a MonoScript.

Okay, that’s kinda weird. Maybe they should add that in an update. It wasn’t really that important but thanks a lot for your help I really appreciate it!