Create UI via script in 5.0

Let’s keep it simple and short:
How to i create UI in Unity 5 with only using a script on an empty GameObject?

This covers subquestions like
How do i create a Button in the script (as GUI.Button seems to be deprecated/legacy)?
How do i create a Canvas so i can manipulate its Render Mode?

That is all for now. The Manual covers the basic knowledge how each component is used but i cannot get any valuable code which would teach me how to do use it.

I don’t care if there are other ways to create and use UI. I want to do it via script if this is at least possible in Unity. I have my reasons for it.

The basic theory works like this…

//Assuming "using UnityEngine.UI;  at the top of your script


GameObject canvasGO = new GameObject();
RectTransform canvasRT = canvasGO.AddComponent<RectTransform>();
Canvas canvasCV = canvasGO.AddComponent<Canvas>();
canvasCV.RenderMode = RenderMode.ScreenSpaceCamera;
Vector3 pos = Camera.main.transform.position;
pos  += Camera.main.transform.forward * 10.0f; 
canvasCV.worldCamera = Camera.main;

GameObject buttonGO = new GameObject();
RectTransform buttonRT = buttonGO.AddComponent<RectTransform>();
buttonRT.SetParent(canvasRT);
buttonRT.sizeDelta = new Vector2(200.0f, 100.0f);
Button buttonBU = buttonGO.AddComponent<Button>();
buttonBU.onClick.AddListener( () => {  Debug.Log("button clicked");  } )
Image buttonIM = buttonGO.AddComponent<Image>();
buttonIM.sprite = Resource.Load("buttonSprite", typeof(Sprite)) as Sprite; 

This is just some example code of course… but it gives you an idea of the process that is required. It’s extensive.

Also, since you mentioned not being able to find the button class, all the UI components are in a separate namespace… so it’s UnityEngine.UI.Button.

You can also get access easily by adding “using UnityEngine.UI;” to the top of your script.