Clickable area around icon in Unity

1.4k Views Asked by At

I'm writing mobile Unity application. I want to add closing (X) icon for one scene. And add some padding around icon to make clickable area bigger ( because icon is not so big).

I wrote next code:

// create button
GameObject buttonContainerObject = new GameObject("XIconContainer", typeof(Button), typeof(RectTransform));
buttonContainerObject.GetComponent<Button>().onClick.AddListener(onClickAction);

// set button location and size
buttonContainerObject.transform.SetParent(canvas.transform);
buttonContainerObject.GetComponent<RectTransform>().sizeDelta = new Vector2(area_width, area_hight)
buttonContainerObject.transform.position = some_position;

// create image
GameObject buttonIconObject = new GameObject("XIconImage", typeof(Image));
buttonIconObject.GetComponent<Image>().sprite = xIconSprite;

// set image location and size
buttonIconObject.transform.SetParent(buttonContainerObject.transform);
buttonIconObject.transform.localPosition = new Vector3(0f, 0f); // in the center of button

But when I build project and tap on button, it responds only if I tap on image, outside image (and inside buttonContainerObject bounds) nothing happens.

What can I do in this situation? Thanks for response.

2

There are 2 best solutions below

2
pasotee On

You can just make a big button and change it's rect transform to be as big as you want and put your icon as a child of the object.

0
Gen1n On

for others reading this, I had similar problem with unity 22. Unlike his case where he wanted to expand the click region, i wanted to contract my region.

I am using Raw image and i changed its raycast padding to achieve my result. Works for both expand and contract. (Works for button, image, rawimage which has raycast padding)

Raw Image Inspector Panel imgur link