According to the manual, you can’t add UI elements directly from code, you need a Prefab. But there is a workaround for this scenario. You create a standard GameObject, add a RectTransform and that’s it. It converts itself to an UI element:
1 2 3 4 5 6 7 8 9 |
public void CreateButton(Transform panel, Vector3 position, Vector2 size, UnityEngine.Events.UnityAction method) { GameObject button = new GameObject(); button.AddComponent<RectTransform>(); button.transform.parent = panel; button.GetComponent<RectTransform>().sizeDelta = size; button.AddComponent<Button>(); button.GetComponent<Button>().onClick.AddListener(method); } |