Search Unity

UI Button color

Discussion in 'UGUI & TextMesh Pro' started by Morseton, Jul 1, 2016.

  1. Morseton

    Morseton

    Joined:
    Jan 15, 2016
    Posts:
    90
    Hello, I have a question regarding the UI Button.

    When you hover your mouse over the button, it fades to a color, is it possible to get the current color of the button?

    Thanks!
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
  3. Morseton

    Morseton

    Joined:
    Jan 15, 2016
    Posts:
    90
    No, I need to know the current color of the button in real-time, while playing. This would make it a lot easier to know if the mouse is hovering the button or not
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,188
    Last edited: Jul 1, 2016
  5. rcalabrezi

    rcalabrezi

    Joined:
    Mar 7, 2015
    Posts:
    3
    I know it's an old topic and the last post has probably pointed the right way to solve what it was asked in first place, but I couldn't find a thing about how to get the Button color in realtime until I figured it out by looking at the UI source code.

    In order to get the color changed by the Button, one just need to check the CanvasRenderer attached to the Graphic component used by the Button, which usually is the Image in the same GameObject.

    Here goes an example:
    Code (CSharp):
    1. public class ColorClone : MonoBehaviour
    2. {
    3.     private Graphic target;
    4.  
    5.     public Graphic Source;
    6.  
    7.     private void Awake()
    8.     {
    9.         this.target = this.GetComponent<Graphic>();
    10.     }
    11.  
    12.     private void LateUpdate()
    13.     {
    14.         this.target.color = this.Source.color * this.Source.canvasRenderer.GetColor();
    15.     }
    16. }
    Add this script to any GameObject that has a Graphic (like an Image) and drag the Graphic used by the Button (the Button GameObject has an Image) to see its color changing as the button state changes.

    Maybe there's a better way to do that, but anyway I hope it can help someone.
     
    chaikadev and Sabrino like this.
  6. Sabrino

    Sabrino

    Joined:
    Aug 8, 2015
    Posts:
    36
    Thank you rcalabrezi, that's super simple and it works perfectly.