• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
Question by EsC369 · Sep 11, 2020 at 06:49 AM · scripting problembuttonsbutton trigger eventsitems

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. alt text


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


forunity4.png (6.0 kB)
Comment

People who like this

0 Show 0
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by EsC369 · Sep 11, 2020 at 09:50 PM

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:

alt text

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);
     }



forunity45.png (183.6 kB)
Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image

Answer by streeetwalker · Sep 11, 2020 at 09:20 AM

@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.

Comment

People who like this

0 Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image EsC369 · Sep 11, 2020 at 06:13 PM 0
Share

WOW! Thanks man! Very informative! And yes, you assumption is true. I will get back at it and see if I can apply any of these approaches. I originally was trying to do it like you said at the bottom, where I was going for button clicks. But I was having trouble determining that as well within the rect transform. I figured the approach I expressed above was the easiest way lol, guess I was wrong.. Nonetheless, would you by chance have any code examples to give me a better push here? I'm honestly fried on this the past 3 days..


also, when you say "Re-author" Im not really sure what you mean? I figured the way everything is set up, they would be attached to each item slot.


As well, how would I go about this in terms of adding this into the newly instantiated slot template?


Or more so, I mainly want to just feed the data thats within the "itemSlot" Instantiation into the button click? Is this possible?

avatar image streeetwalker EsC369 · Sep 11, 2020 at 06:28 PM 0
Share

I'm not sure what the best way is. There are trade offs - some require more authoring at the prefab level, and some require more planning at the scripting level. Mostly these are wicked problems that have no perfect solution, and you have to balance a lot of factors.

One big consideration is, how easy is it to go back in and make changes? What if you decide that not all inventory slots are the same size? What if you decide to change the number of slots? You can get in a position where you have to redo everything, and the balance is where you see yourself doing that enough times that it might have been better to do it all in script, which takes a lot of planning up front, but saves time if you can just change a few numbers in an inspector.

Probably most often there is a happy medium between the two.

Sorry, by re-author I simply mean to modify the prefab. I saw you were having problems connecting the button click with the slot that got clicked on, so I just mean to modify the prefab to cache all that up front.

Just to reinforce what I wrote up there, if you put the script that reports which slot got clicked on to the button itself, and you populate a field on that button's script with the index of the slot, you'll solve the problem you were having. Caching a reference to the button's script in a script on the parent prefab will make it easy to populate that field when you instantiate the prefab.

avatar image EsC369 streeetwalker · Sep 11, 2020 at 06:43 PM 0
Share

I see... Thank you for this insight. The issue im having here though, is I have NO IDEA which element within the UI List, is being clicked.. Of course if I put which slot is being clicked, but thats my issue... How do I determine which slot is being clicked? Im just not sure how to go about this with code lol.. Ive been racking my brain through trial and error. I will try my best to apply what your explaining here. Thanks for the help, and please let me know if you can simply throw out a code example for me lol. That would do wonders if its not to much trouble?

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

317 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Detect if UI button clicked 1 Answer

Wanting make shop system, how can I disable this condition after item sold? 0 Answers

Player Upgrade Screen - Button Upgrades keep resetting! 0 Answers

How to fix button clones that aren't working? 0 Answers

How can I make a UI button's action happen before `Input.GetMouseButtonDown` action in another script? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges