Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • 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
11
Question by TimBur · Sep 26, 2014 at 12:36 AM · c#guievent4.6

Example of setting up a button OnClick event via scripting?

FYI - this is cross posted from the 4.6 forum. I wasn't getting any hits there, so I figured I'd try here as well.

My question is this:

Can anyone point me to an example of setting up a button OnClick event via scripting in 4.6?

The new GUI tutorials do a good job of showing how to use the inspector to make a button call arbitrary functions on an OnClick event (e.g. here). I figure there must be a way to do the same thing via scripting - to give a button a list of functions (and arguments for those functions) to call when it is clicked. However, I'm getting lost in the documentation (e.g. Event Tools, ButtonClickedEvent). There are lots of functions, but only very brief descriptions, and the meaning is beyond me.

Any advice would be greatly appreciated.

Comment
Add comment
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
41

Answer by nur farazi · Jan 08, 2015 at 07:55 AM

 for (int i =1; i<=50; i++) {
             
   button.name=PlayerPrefs.GetString ("LeveltextNumber" + i.ToString ());
 
 
   button.button.onClick.AddListener(delegate { test(button.name); });
 
 }

 public void test(string ok){

     Debug.Log (ok);

 }


it should solve the problem

please accept the answer if this solve your problem

Comment
Add comment · Show 15 · 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 Redwolve · Jan 12, 2015 at 01:07 PM 0
Share

How would you accomplish this in uJS?

avatar image nur farazi · Jan 12, 2015 at 01:53 PM 0
Share

:( , ( $$anonymous$$an of c# ) here

avatar image daneislazy · Feb 07, 2015 at 11:10 AM 0
Share

@Redwolve it's similar but ins$$anonymous$$d of delegate... you pass in function() { test(button.name); } or just the whole function if you want. Though it's worth noting that some variables won't pass properly, but Game Objects seem to work fine. Also if your function doesn't have any variables to pass you can just pass in the name of the function .AddListener(test);

avatar image Strass_Productions · Sep 19, 2016 at 01:48 PM 1
Share

thank you very much nur farazi. It works

but I don't get the point of the loop. What is it for ?

How ever i have an issue : i'm trying to create multiple buttons in a loop, then assign a onClick event to each of them. The Event is supposed to call Test (with a increasing int), yet it seams to call Test with the last number iterated through.

 void Start () {
         for (int i = 0; i < 5; ++i ) {
             GameObject button = Instantiate (prefab) as GameObject;
             button.GetComponent<Button> ().onClick.AddListener ( delegate { Test (i); });
         }
     }
 
     void Test ( int id ) {
         Debug.Log (id.ToString ());
     }
avatar image hitarthdoc1994 Strass_Productions · Nov 16, 2016 at 09:48 AM 0
Share

@Strass_Productions Hi, I have encountered the same issue almost after a YEAR. I was hopping you could have a solution to this Problem.

Thanking you, Hitarth Doctor

avatar image hitarthdoc1994 hitarthdoc1994 · Nov 16, 2016 at 10:01 AM 2
Share

@Strass_Productions Hi, I have encountered the same issue almost after a YEAR. I JUST solved the problem by using a Coroutine to do the following:

 button.GetComponent<Button> ().onClick.AddListener ( delegate { Test (i); });

Using this the calls get stored in the stack until the for loop ends. Giving us the desierd Results.

Hitarth Doctor

Show more comments
avatar image Kobrasadetin · Mar 12, 2018 at 11:05 PM 4
Share

For everyone struggling with the problem when using integers ins$$anonymous$$d of strings in the loop: You can force the reservation of memory for each integer by the 'new' keyword. So the loop with integers becomes:

 for (int i =1; i<=50; i++)
 {
     GameObject button = Instantiate (prefab) as GameObject;
     int x = new int();
     x = i;
     button.GetComponent<Button> ().onClick.AddListener ( delegate { Test (x); });
 }
 void Test ( int id ) {
     Debug.Log (id.ToString ());
 }










Show more comments
avatar image
4

Answer by LynnPi · Sep 26, 2014 at 03:30 AM

Just like this: xxxBtn.onClick.AddListener(YourDisposeFunction);

Comment
Add comment · 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 TimBur · Sep 26, 2014 at 04:23 AM 0
Share

Hmm. That seems pretty easy. I'll give it a try. But then what about arguments? Using the inspector, you can fix it so that when a function is called, it is passed a single, pre-deter$$anonymous$$ed argument.

avatar image Stardog · Dec 11, 2014 at 04:36 PM 0
Share

$$anonymous$$ake sure you have "using UnityEngine.UI;" at the top of your script.

avatar image PatBGames · Jan 06, 2015 at 10:33 PM 2
Share

For argument use:

xxxBtn.onClick.AddListener(delegate { YourDisposeFunction(YourArgument); });

Note : The new event won't appears in inspector at runtime, but it will be called on click.

avatar image Elenesski · Apr 14, 2015 at 04:53 AM 1
Share

You can also do it with a lamba expression too:

 BUTTON.onClick.AddListener(() => YourFunction(YourParam));

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.

Follow this Question

Answers Answers and Comments

13 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

Related Questions

When I pause my game and enable canvas and then resume my keyboard starts controlling the menu... 1 Answer

Unity 4.6B UI Scrollbar Usage 1 Answer

how to display the damage value from a mob 1 Answer

What is the best way to concatenate string to create an interaction logging console? 4 Answers

Unity editor works but the built game doesnt. 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