Hi,
I want to create a UI Button from code without Prefabs or anything else from a static class.
My problem is that the button doesn’t work as a button.
It’s not changing it’s color when hightlighted or pressed and doesn’t call the onClick Event.
This is my code:
GameObject b1 = new GameObject();
b1.name = "OK";
b1.AddComponent<RectTransform>().sizeDelta = new Vector2(100f, 25f);
b1.AddComponent<Image>();
button1 = b1.AddComponent<Button>();
button1.transform.SetParent(panel.transform);
button1.GetComponent<RectTransform>().transform.localPosition = new Vector3((panel.GetComponent<RectTransform>().sizeDelta.x / 2f) - (button1.GetComponent<RectTransform>().sizeDelta.x / 2f), -((panel.GetComponent<RectTransform>().sizeDelta.y / 2f) - (button1.GetComponent<RectTransform>().sizeDelta.y / 2f)));
button1.onClick.AddListener(delegate{
OnButtonClicked(button1.name);
});
I think i’m adding all needed components to the Button:
-RectTransform + Image
-Button
And I’m adding a listener, so whats wrong?
Thankful for any help!