Script spawns another script within the gameobject

Is it possible to have a script spawn another script in the same gameObject? I attempted to do so with Instantiate, but it came up with an error.

To create a new instance of a regular class you use the new keyword. The Instantiate method just creates new instances of game objects from originals (like prefabs or existing game objects). Here’s two example for instantiating new classes using C#. The second allows you to initialize script variables without constructors.

Foo foo = new Foo();
Bar bar = new Bar
{
    someVar = someValue,
    otherVar = otherValue
};

If the class you are trying to instantiate inherits from mono behaviour, then your class is turned into a component. Then you can add a class/component using AddComponent:

ScriptName script = gameObject.AddComponent<ScriptName>();
script.publicMember = value;

The method returns a reference to the script attached, you can then modify it.

The other way is to create using the usual C# way if your script does not inherits from MonoBehaviour (if it does this method will return an error):

ScriptName script = new ScriptName();
script.publicMember = value;