Add a script to a gameobject that doesn't exist yet

I have a script that creates a cube but I need to add a script to that newly created cube. How would i do this?

Right after you create the cube (presumably using GameObject.CreatePrimitive?) you can add whatever component you want, including scripts, by calling AddComponent on the newly created object.

Like so:

    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
    cube.AddComponent<YourScriptHere>();

Use GameObject.AddComponent API to add Script to a GameObject.

In C#

ScriptClass scriptVar = (ScriptClass)newGameObject.AddComponent<ScriptClass>();

In Js

var scriptVar = newGameObject.AddComponent(ScriptClass);