Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

UI Buttons Linked Animations

Discussion in 'UGUI & TextMesh Pro' started by Plummers, Apr 18, 2018.

  1. Plummers

    Plummers

    Joined:
    Oct 29, 2015
    Posts:
    35
    Hi, I have three buttons in my game menu. When one button is highlighted (hovered over) I want the other two buttons to reduce in size. How do I link the animations of the other buttons to the fact that the third button has been highlighted? An example of this in a game is Mini Metro.

    Thanks in advance,
    JP
     
  2. Hosnkobf

    Hosnkobf

    Joined:
    Aug 23, 2016
    Posts:
    1,096
    There is no way out of the box to do this, I guess... Probably it is possible with animation transitions, but this will become messy pretty quickly, I guess...

    What you can do is Adding an EventTrigger component to your Buttons. There you can add scripts callbacks for OnPointerEnter and OnPointerExit.

    Create a custom MonoBehaviour script which knows all the buttons. It has two functions which both has an argument of type Transform. One function is for enter, one is for exit; the argument specifies which button got the focus.

    Then you can add that script to one GameObject in your scene and link it with all the buttons / their event triggers.

    Here an (untested) example code:
    Code (CSharp):
    1. public class ButtonScaler : MonoBehaviour
    2. {
    3.     [SerializeField]
    4.     List<Transform> _allButtons; // assigned inside unity
    5.  
    6.     // added to event trigger of all buttons "OnPointerEnter"
    7.     public void FocusButton(Transform focusedButton)
    8.     {
    9.         ApplyButtonScales(focusedButton, 1.1f, 0.9f);
    10.     }
    11.  
    12.     // added to event trigger of all buttons "OnPointerExit"
    13.     public void UnfocusButton(Transform focusedButton)
    14.     {
    15.         ApplyButtonScales(focusedButton, 1f, 1f);
    16.     }
    17.  
    18.     void ApplyButtonScales(Transform focusedButton, float focusedScale, float othersScale)
    19.     {
    20.         foreach(Transform tr in _allButtons)
    21.         {
    22.             // set the scale directly... A cool idea would be to make a simple animation instead.
    23.             if(tr == focusedButton)
    24.             {
    25.                 tr.localScale = new Vector3(focusedScale, focusedScale, 1);
    26.             }
    27.             else
    28.             {
    29.                 tr.localScale = new Vector3(othersScale, othersScale, 1);
    30.             }
    31.         }
    32.     }
    33. }
    34.