How to get the button gameObject when it is clicked?

I am creating an inventory UI and I am displaying my items in a scrollable list. Each UI element in this list has a button component and is instantiated during runtime. When I click the item in the list I have a menu that pops up giving options as to what to do with the item. I have attached a container script with all of the items basic data to the same UI element with the button so I don’t have to keep iterating through my item database each time I want to reference a specific item. When I click the button I want to be able to store the gameObject the button component is attached to for future use. How can I achieve this?

Also if anyone knows, how can I make the menu that pops up when I click the button move to the position of the mouse?

I haven’t tried this before, but [UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject](https://docs.unity3d.com/ScriptReference/EventSystems.EventSystem-currentSelectedGameObject.html) might get you what you need, if called during the button event handler.

21 Likes

Well the simple but definitely not the best way is:

  1. Within a script put a ‘public static GameObject selectedButton;’
  2. Then when you call the code for a button press you would use ‘SomeScript.selectedButton = gameObject;’
1 Like

Pass the gameObject of the button as a paramter while your are adding event listener to the ui button Hope that helps)

GameObject myButtonGameObject = myButton.gameObject;

myButton.onClick.AddListener(() => {LogName(myButtonGameObject); });

public void LogName(GameObject buttonGameObject = null){
    Debug.Log(myButtonGameObject);
}

Note: The given approach is useful, when you need dynamicly show the clicked buttons name, but if you know the exact button, you can make a public field for the myButton and get the name without passing any parameters.

11 Likes

Thanks bro

This really helped. Thanks!

this is great!

I just pass a Button as parameter and after get the reference from inspector… works well to me.

I just needed the text of the button, but modifying it for the entire button, this worked (I have more code of course, but this is the basics):

void AddTask(string task){
   Button taskItem = new Button();
   taskItem.text = task;
   taskItem.clicked += () => ShowTask(taskItem);
}
void ShowTask(Button button){
   Debug.Log(button.text + " task button pressed");
}

I’m currently using a slightly different method, which is to request a parameter of type GameObject when the button calls the method. Then, I link the script to the OnClick() field in the Button → select the correct method and link the GameObject of that Button.

public void Checker_DebugLog(GameObject button)
{
Debug.Log($“THIS BUTTON IS WORK - {button.name}”);
}

9716293--1388887--upload_2024-3-22_16-43-28.png

You are an absolute champion, thank you.