How to Instantiate UI elements via C#

So I’m new to Unity and I’ve currently built a simple UI for a prototype and want to not be so dependent on the visual editor so I’m trying to figure out how to properly instantiate prefabs like buttons and panels. Right now I’m trying to just make one of my buttons that I have as a prefab but I’m having trouble. I’ve managed to load a prefab canvas, and a button with it’s parent as a canvas but they are both type GameObjects and not Canvas and Button. I’ve tried changing the below code to types Canvas and Button but the button doesn’t show up so I’m having trouble understanding what exactly it is I need to do.

void Awake () {

		GameObject prefab = Resources.Load ("Ability1") as GameObject;
		GameObject prefab2 = Resources.Load ("Canvas GUI") as GameObject;
		GameObject instance = Instantiate (prefab, transform.position, transform.rotation) as GameObject;
		GameObject instance2 = Instantiate (prefab2, transform.position, transform.rotation) as GameObject;
		instance.transform.SetParent(instance2.transform, false);

Can I get some tips on what I need to do/look up or if what I’m doing is not good coding practice? The code above correctly displays my button in the center of the screen, but I can’t access button features like onClick. I haven’t found another way to do it searching online so here I am.


You need instantiate UI Components “Canvas” child

You’ll also need the EventSystem along with the Canvas in the prefab so that events are received. Between the whole point of Unity and the Editor is to make the process fast and easier and it is highly not recommended to instantiate gameobjects through the script that you can create in the editor and put them to use. Only if you want to use a particular custom gameobject multiple times, you may use prefabs.