How can I check if a UI button is selected?

How can I check in script if a Button bla = new Button(); is selected? Not clicked on but just selected.

Thanks in advance :)!

Compare your button’s gameObject with EventSystem.current.currentSelectedGameObject.
EventSystem requires the namespace UnityEngine.EventSystems

There are a few ways you can do this.

  1. You can use EventSystems and subscribe to OnSelect event
    Documentation Reference
using UnityEngine.EventSystems; // Required when using Event data.

public class ExampleClass : MonoBehaviour, ISelectHandler // required interface for OnSelect
{
    //Do this when the selectable UI object is selected.
    public void OnSelect(BaseEventData eventData)
    {
        Debug.Log(this.gameObject.name + " was selected");
    }
}
  1. You can use EventSystem to compare a gameObject with selected game object
public GameObject ButtonGameObject;

public void Update()
{
    // Compare selected gameObject with referenced Button gameObject
    if(EventSystem.currentSelectedGameObject == ButtonGameObject)
    {
        Debug.Log(this.ButtonGameObject.name + " was selected");
    }
}

Using gameobject comparison in Update is inefficient and kinda silly if your game is not built on selecting UI buttons only. So your best bet is to mix up first soultion with a comparison idea.

using UnityEngine.EventSystems;

public class ExampleClass : MonoBehaviour, ISelectHandler
{
    public void OnSelect(BaseEventData eventData)
    {
        if(eventData.selectedObject == ButtonGameObject)
        {
            Debug.Log(this.ButtonGameObject.name + " was selected");
        }
    }
}
  1. Last but not least. You simply listen to OnMouseEnter/OnMouseExit and do your stuff. It’s not a 100% way to check if a button was selected, but in most cases it works.
public bool Selected;
 
void OnMouseEnter()
{
    selected = true;
    Debug.Log("Button was selected");
}
 
void OnMouseExit()
{
    selected = false;
    Debug.Log("Button was deselected");
}

Wouldn’t this work just fine?

void OnMouseOver(){
    Debug.Log("Button Selected");
}

Could also;

void OnMouseEnter(){
    Debug.Log("Button Selected");
}

void OnMouseExit(){
    Debug.Log("Button Unselected");
}

Bit better than my last answer.

Just wanted to add that if you do want to check selected via the Update Function use
EventSystem.current.currentSelectedGameObject
instead of EventSystem.currentSelectedGameObject
,Just wanted to add that if you do want to check selected via the Update Function use
EventSystem.current.currentSelectedGameObject
insead of EventSystem.currentSelectedGameObject

Don’t know if this is exactly what you wanted but it’s what I wanted when I came across your question.

The class Selectable has the property currentSelectionState that you can check to see what state it’s on, so to check if it’s selected you would check

currentSelectionState == SelectionState.Selected

(Button, Toggle, Slider, etc. all inherit from Selectable)