Attach main script to game object programmatically?

Bear with me, I’ve been learning Unity for all of 3 hours and half of that was trying to research this question. I have a fresh project, 2d, with only the main camera. I right-clicked my Asset folder, Create > C# script (Main.cs) and added some code to draw a rectangle at a certain position in the OnGui method.

However, I’ve gathered that this won’t work until the script is attached to any game object in the hierarchy. Seems idiosyncratic, but whatever. Is it possible to programmatically attach my script (Main) to the main camera?

I tried this in Start but to no avail:

I’d imagine there are a gazillion ways of doing this through the inspector panels or other drag-drop goodies but, hey I’m idiosyncratic myself and like doing everything programmatically - if possible. Coding purist, if you will.

So, is this possible?

So GameObject.AddComponent(“ClassName”) as ClassName; is the correct code, but, unity only runs scripts that are attached to gameobjects. That line needs to be in a script that is attached to an object. You can push the problem back to another script, but there needs to be a script on a gameobject at some point.

You theoretically write one script that creates all your other scripts and gameobjects and go from there.

Also, OnGui() is pretty outdated. The new UI system is based around objects in the scene rather than code, so you probably won’t like it.