• 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 /
avatar image
Question by rhughes · Aug 16, 2015 at 08:22 AM · unity 5

Find caller of dynamically added button click's listener

I am adding a list of buttons in code for which I would like to add a click listener.

I am able to add the listener, the issue is I would like to know the button that called the listener.

I have tried the following method, but the passed value to the listener is always the same:

 foreach (...)
 {
     var button = (Button)GameObject.Instantiate(...);

     packIndex++;

     button.onClick.AddListener(() => this.OnButtonClick(packIndex));
 }

 public void OnButtonClick(int idx)
 {
     // idx is always the latest value in the above loop
 }

TL;DR

How do you find the caller from a button click listener?

Comment
postrowski

People who like this

1 Show 1
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 Glurth · Aug 16, 2015 at 02:13 PM 0
Share

I don't think you will be able to pass it as a parameter because AddListenes specifies a UnityAction, which has no parameters.

I suggest you derive a new class from BUTTON, and add a member variable called packIndex; Also add a new function to the class handleclick().

Then, you can do something like this: (uncomplied or tested)

 ...
 packIndex++;
 button.packIndex=PackIndex;
 button.onClick.AddListener(() => button.HandleClick());
 ...
 
 
 //defined inside your new button derived class.
 public void HandleClick()
 {
      //use button member variable PackIndex.  Note with this method you may no longer need to keep those ID number, instead you can use "this".
 
 }

2 Replies

  • Sort: 
avatar image
Best Answer

Answer by troien · Aug 16, 2015 at 02:13 PM

I'm not sure, but I believe I had a similar problem once and it had to do with the scope in which packIndex exists (it is defined outside of the for loop), and thus each lambda delegate shares the same int (which has been set to the latest value of the loop by the time the delegate is called.

I believe fixing this is as simple as creating a copy of the index inside the foreach loop and use that instead. Like so:

 foreach (...)
 {
     var button = (Button)GameObject.Instantiate(...);
 
     packIndex++;
     int copiedIndex = packIndex;
 
     button.onClick.AddListener(() => this.OnButtonClick(copiedIndex));
 }
 
 public void OnButtonClick(int idx)
 {
     // do stuffs here
 }
Comment
rhughes
postrowski

People who like this

2 Show 1 · 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 rhughes · Aug 16, 2015 at 03:15 PM 0
Share

This was technically the answer. In my case though, there was one more thing:

This answer will not work in a co-routine. This code must be called in the standard way. See http://forum.unity3d.com/threads/how-to-add-non-persistent-unityaction-with-a-single-parameter-to-a-buttons-onclick-event.267047/ for details on this.

avatar image

Answer by Cherno · Aug 16, 2015 at 02:24 PM

I did it like this:

Add the Listener via script, and give it a method which accepts a custom class instance as a parameter. This class will hold the button that is clicked as well as any other data that is neded for the medthod.

 public class ButtonClickParameter {
      public Button button;
 }
 
 public Button myButton;

 void Start() {
       ButtonClickParameter buttonClickParameter = new ButtonClickParameter();
       buttonClickParameter.button = myButton;
       myButton.onClick.AddListener(delegate { ButtonClick(buttonClickParameter ); });
  }
                 
         
 
 
 private void ButtonClick(ButtonClickParameter bcp) {
      Debug.Log(bcp.button.name);
 }
 
Comment
rhughes

People who like this

1 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

Unity Answers is in Read-Only mode

Unity Answers content will be migrated to a new Community platform and we are aiming to launch a public beta by June 9. Please note, Unity Answers is now in read-only so we can prepare for the final data migration.

For more information and updates, please read our full announcement thread in the Unity Forum.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Cannot drag text object into inspector 2 Answers

How to set value to rigidbody and when transform it how to save the value? 0 Answers

custom object in place of leap hands controller . 0 Answers

Compact Wordle Graphics in Unity3D 0 Answers

"Error building Player" WebGL build error 2 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