3

I'm still quite new to Unity and I'd appreciate any help on this problem.

I have this setup which works well using the screen resolution I was designing on. I believe the UI elements scales well when I change the resolution but I just found out that the colliders that I've made (red lines in the image) don't. Currently, I'm using edge colliders added to the canvas. I've also tried adding individual edge colliders to each panel. Then I tried box colliders. I've tried turning the panels + colliders into prefabs. All to no avail. I've also tried setting the points of the edge colliders via script so that they're always wrapped around the panels but I can't get any collision (note: I don't know how to show/render this runtime-generated colliders so I'm not perfectly sure that they're exactly how I want them to be).

tldr; does anybody know how to make colliders scale or wrap around the UI elements they're bound to?

ui layout image

Syscall
  • 19,327
  • 10
  • 37
  • 52
Ferdie
  • 33
  • 1
  • 6
  • 1
    Well, using colliders in UI elements may not gonna work. Try to add collider in non-UI elements (outside the canvas) and retain its proportion if it is keep changing in different resolutions – Hamza Hasan Feb 18 '16 at 10:15
  • It works but I can't get it to scale. someone also told me that physics on UI elements usually lead to poor performance so I'm open to converting them into actual game objects. I was just trying using prefabs and although I can get them to scale, I can't seem to anchor them using the editor. I have no idea whether it's possible via script either. – Ferdie Feb 18 '16 at 11:51
  • 2
    your someone is right. Well, as you are developing in 2D environment, you can easily get screen width and height, so make an object of unit size, add a box collider 2d, check the UI ratio from screen, for example you have left panel is 12.5% of total width, so scale and position it accordingly – Hamza Hasan Feb 18 '16 at 11:55
  • 1
    I see. So, it is indeed doable via script. Am I right that it can't be done via editor though? Or did I just miss something? – Ferdie Feb 18 '16 at 12:10
  • 1
    you are right, You'd do it through script – Hamza Hasan Feb 18 '16 at 12:14
  • I see. I'd try this. Thank you so much for the help! – Ferdie Feb 18 '16 at 12:17

1 Answers1

6

So, colliders working fine with UI. Keep in mind that colliders work in units, but the canvas in pixels.

If you need to set BoxCollider2D component size with image size, you need to check the value you're using for the Reference Pixels per Unit parameter on your Canvas Scaler.

This mean, that if your image 100px in width you need to set on collider scale 100 units.

This is what you need to do:

gameObject.GetComponent<BoxCollider2D>().size = new Vector2 (
    gameObject.GetComponent<RectTransform>().sizeDelta.x,
    gameObject.GetComponent<RectTransform>().sizeDelta.y
    );
Syscall
  • 19,327
  • 10
  • 37
  • 52