- Home /
Creating working UI Button from Script?
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!
Try instantiating a button prefab first, where you only have to add the delegate, ins$$anonymous$$d of creating a GameObject from scratch.
Answer by Munchy2007 · Jun 10, 2016 at 11:24 AM
Have you got an eventsystem in the scene and a graphics raycaster on the camera?
Thanks, I forgot to add a graphics raycaster on the camera.
You're welcome, glad I could help.
Would you be kind enough to mark this as accepted, thanks.