How to grab button object within Instantiated UI Template?

What im trying to do here, is just havea functional button that sends the value of its element placment within my list of inventory items.
When I show inventory, it shows the items that I picked up with said values and sprites, etc.

Now my issue is im trying to determine which one I click within my list on the UI.


Now What ive done so far, is when the item template is instantiated, I just added a button witihn this UI hierarchy with a script attached to it. Now so far, it is functional, it legit says “Button clicked” When clicking on the said button on the said item. But my issue is I need to pull which item it is… Now what ive done so far, is just created a counter thats starts at 0, and each time it iterate my items within the inventory list, it sets the number to the according placement they are within the array/list. So, each item, does have the particular element of placement attached to it… I just cant figure out how to grab that number depending on button click?


Currently is my code below, trying to basically grab the button gameobject from my newly instantiated UI template, and simply change the value within the “Button Script” Thus, pinning the element placement.


Im not really sure if this approach im taking is the right way. But here is my code below:

foreach (Item item in inventory.GetItemList())
        {
            // *NOTE* Here Is Where We Grab And Set The Data Into The INstantiated Slots witin out bag list UI:--------------

            
            // Instantiate the slot template:
            GameObject itemSlot = Instantiate(itemSlotTemplate) as GameObject;
            itemSlot.SetActive(true);

            // Add to ItemSlotList, to remove duplicates:
            itemSlotList.Add(itemSlot);

            // Here below, we are changing the values of the item name, amount and sprite image to the UI INventory accordingly:------
            itemSlot.GetComponent<ItemSlotList>().SetText(item.itemType.ToString(), item.amount.ToString(), item.GetSprite(), myNumber);

            // Attempt Below: HERE IS WHERE IM GETTTING STUCK AT: SHOWING SOME OF MY OTHER ATTEMPS BELOW:
            var btn = GameObject.Find("Button").GetComponent<Button>();
            btn.GetComponent<ButtonScript>().SetVal(myNumber);

            // HERE!!! SOMEHOW TRANFER THE "MYnuMBER" tO THE bUTTON sCRIPT!!------------------
            // itemSlot.GetComponent<ButtonClicked>().listElem = myNumber;
            // itemSlot.GetComponent<ButtonScript>().listElem = myNumber;

            // btn = FindObjectOfType<Button>().transform;
            // btn = itemSlot.transform.Find("Button");
            // Debug.Log("Test hasdsadadasdsd: "+ btn);
            // btn.GetComponent<ButtonScript>().SetVal(myNumber);
}

Here is my Button Script:

public class ButtonScript : MonoBehaviour
{
    public int listElem;
    
    public void BtnPrint()
    {
        Debug.Log("TEST HERE BT#: "+ listElem);
    }

    public void SetVal(int num)
    {
        listElem = num;
    }
    
}

Any advice is appreciated: Heres my Hierarchy: FYI The ButtonScript is attached to the “ButtonScript Gameobject” Then from there, is feed into the “Onclick” Functionality of the button within my item slot template.
167312-forunity4.png


Been stuck on this for quite some time, any help is greatly appreciated, thanks.


@EsC369, correct me, but it seems like you are adding inventory slots dynamically, and you want to know what inventory slot gets click on?

I think you are already tracking what inventory slot gets added and where, so you have a index to each inventory slot?

If the above summary of mine is true, then there are several ways you can go about getting an arbitrarily selected slot.

Your current approach is to embed the slot tracking information (its index) into a button that will spit back this information when clicked on. But it seems you are making it harder than it needs to be:

Your template is a prefab, so re-author the prefab so that everything is hardwired into the slot script instead of relying on these Find statements, which are expensive.

Author the button in to the prefab, and put a script on the button and not on a separate object. The button script will hold a reference to the slot index just has you have shown. Then on the slot script, reference the button script directly in a public field by dragging the button to the slot script’s public field. That way you will have an instant reference to the slot the button is in, and can report or pass it to whatever when you click on the button.

Another approach that is even simpler is to dispense with the button all together and simply get mouse clicks using the camera. Get the x and y of the mouse click, and determine if that is within the rectangle of your inventory, and you can easily determine which slot the click occurred in by a division operation. You just need to know how many slots there are in x and y dimensions and what their widths and heights are. Note this approach only works if all your inventory slots are all the same size and arranged in a regular grid.

Man I just cant win… So I changed the button into a gameobject that is just a picture of the button now. Utilized the clicking event system to see which gameobject is being clicked! AWESOME! Great progress! HOWEVER… My goal here was to now change the particular gameobject to the number as to thus, pinpoint which number is attached to which button. Now this code actually works… Kinda… It does change the game object name to be “Delete_Button_0” - how ever my items.


Looking at my Hierarchy, you can see the the gamebobjects are infact changing to the new names with numbers at the end. BUT… For some reason, when I click on it still… It still says regular “Delete_Button”??? Can someone please just show me some code that explains how to go about this… Literally all I need is the item placement… From there I can iterate through the list and grab the desired item, and thus all the data attached to it.


How the heck do I grab this number? And why is the clicking method still grabbing the regular game object named “Button” Rather than the newly changed ones with numbers? Thanks.

Code:

string test = itemSlot.transform.Find("Delete_Button_Obj").name = "Delete_Button"+ myNumber; Debug.Log("Tets hereasdsadada"+ test);

Image:

UPDATE:

My gosh… So I realize what I was doing, was only changing the gameobject and thus, (for some reason) it was still registering the button Image named" Delete_Button" itself, rather than the gameobject named “Delete_button_Obj1-10, etc.” Like I thought it would. Now the only reason I even stuck it inside a game object, was because I stupidly thought I couldnt change the name of the image itself. (As the Button is now just an image)
But, I realized you could, at that moment, I adjusted it to just changing the name of the image itself, rather than the game object and POOF! Everything finally worked as I was hoping it to!


Definitely inefficient, but all I wanted here, was to pinpoint WHICH element within the list was being clicked, and although that was kinda janky, this definitely achieved that goal. Thanks to all that helped!

And Im still very curious to see more efficient and better ways of achieving what I was trying to do here. So please dont hesitate to give more insight!


Thanks guys!

P.S. One importunate piece of code I left out that really contributed to this is throwing this somewhere witih my ItemListController:

public void OnPointerClick(PointerEventData eventData)
    {
        clickedName = eventData.pointerCurrentRaycast.gameObject.name;
        Debug.Log("Clicked: "+ clickedName);
    }