Search Unity

Button pressed state for both left and right click?

Discussion in 'Scripting' started by jwalden, Sep 10, 2019.

  1. jwalden

    jwalden

    Joined:
    May 30, 2017
    Posts:
    62
    Hey guys, I have a button that can be left clicked or right clicked.

    On left click it activates the pressed state as usual, but I can't find a way to have it enter a pressed state on the right click.

    Any pointers?

    Here is the current script:

    Code (CSharp):
    1.     public void OnPointerClick(PointerEventData eventData)
    2.     {
    3.         if (eventData.button == PointerEventData.InputButton.Left)
    4.         {
    5.             //call add based on index
    6.             Debug.Log("Left click");
    7.         }
    8.         else if (eventData.button == PointerEventData.InputButton.Right)
    9.         {
    10.             //call reduction based on index
    11.             Debug.Log("Right click");
    12.         }
    13.     }
    Thanks in advance.
     
  2. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
  3. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    What exactly do you mean by "pressed state"? What is causing that to happen on left-click?
     
  4. jwalden

    jwalden

    Joined:
    May 30, 2017
    Posts:
    62
    Ah ok, so I'll explain.

    Pressed state on the button is the colour that the button changes to (or that is added on top of the original color) when it is clicked.
    Basically it's the flash that happens when you click a button in Unity.

    This happens automatically on left click, but not so on right click. I thought that by invoking the OnClick method that it would activate the button flash, but that doesn't seem to work.

    Alternatively I will just have to manually lerp the colour of the button itself every time I left or right click - but just wanted to see if there was an easier solution first that I was missing :)
     
  5. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    OK, I am guessing that you have a Button component attached to your object? That color transition is a result of the Button component and has nothing to do with any of the code you posted. If you attach your code to an object with an Image component but no Button component, I believe you'll find it doesn't change color for either mouse button.

    I'm not sure if there's any practical way to extract the Button state logic and apply it to other cases.

    If you want to write your own, you can use CrossFadeColor to do the tweening for you; you'll just need to write the logic for when it should switch to what color.