Create Button from code, without any prefabs

I need to create buttons in code (C#), without using any prefabs.
What is the flow?
A Button would need this stuff and possibly more:

  • gameobject
  • recttransform
  • Button script
  • Optionally an image and/or text, and possibly other images/texts for other states than the normal.

Unity 4.6. No OnGUI please. And no prefabs.

Create a button in your scene and check what structure and component it has.

A default button created has a parent button game object which has a child text object which you can remove if not required.

A button game object has following components:

  • Rect Transform
  • Canvas Renderer.
  • Image Script.
  • Button Script.

The optional child text object has following components:

  • Rect Transform.
  • Canvas Renderer.
  • Text Script.

So to create a button via C# simply:

  • Create an empty game object.
  • Add all the above components required to it.
  • Set values for various properties from those components.
  • (Optional) Add a child empty game object as text and add required components to it and set properties for those components.
  • Make your button game object child of your Canvas and position it accordingly on screen.