Search Unity

2d button - round corners

Discussion in '2D' started by internetxpn, May 26, 2017.

  1. internetxpn

    internetxpn

    Joined:
    May 19, 2017
    Posts:
    8
    Hi dudes,

    i want to create a button with round corners and with a white border. I dont want to use *.png because i want to change the filled color with a script. (single point of control) How is that possible?

    any ideas?
     
  2. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    :D
    Did you tried just overlap button with the border image (change hierarchy order or child) ?
     
    Last edited: May 26, 2017
  3. internetxpn

    internetxpn

    Joined:
    May 19, 2017
    Posts:
    8
    yes but i think that is just a dirty trick :X
     
  4. vakabaka

    vakabaka

    Joined:
    Jul 21, 2014
    Posts:
    1,153
    You can't be honest in the modern world, just be careful that other don't know about your dirty things (and the UI is looking ok on different sizes) :(
     
  5. internetxpn

    internetxpn

    Joined:
    May 19, 2017
    Posts:
    8
    hahahaha thank you for your support - if there is no other method for success i have no choice. But i feel like balrog vs gandalf (unity) "you shall not pass!"
     
  6. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,807
    Make a white button png texture with rounded corners and transparent background, use the Image component's 9-slicing feature to preserve the corners for resizing.

    Use the color field on the Image component to tint the button different colors.

    That is how the default unity button image works.

    Then apply a white colored square behind it as mentioned previously for the border. There are more complex ways to do this with shaders, but you don't need to do that. A simple 2 Image setup works.

    If you wanted it to feel more like one thing, give the parent object a script to control both child image colors, so you have one point of control with two color fields.
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.UI;
    3. public class MyButton : MonoBehaviour {
    4.  
    5.     [Header("Button")]
    6.     public Image button;
    7.     public Color buttonColor;
    8.  
    9.     [Header("Background")]
    10.     public Image background;
    11.     public Color backgroundColor;
    12.  
    13.     private void OnValidate() {
    14.         if(button != null) {
    15.             button.color = buttonColor;
    16.         }
    17.         if(background != null) {
    18.             background.color = backgroundColor;
    19.         }
    20.     }
    21. }
    You could even extend the Button class with new fields for a background image if you wanted.
     
    Last edited: May 26, 2017