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
5
Question by Ruarc88 · May 27, 2015 at 11:08 AM · uibuttononclickfunction call

Unity 5.0.2f1 UI Button OnClick Function

This is my first attempt at using Unity so go easy on me. I'm trying to assign a function to a button's OnClick event but I can't for the life of me get it assigned. The little information I've found says it should work but I can't seem to get it working.

The function:

 using UnityEngine;
 using System.Collections;
 
  public class scriptButtonQuit : MonoBehaviour {
  
      public void onClick(){
          // Save game data
  
          // Close game
          scriptMain.Log ("Application Closing");
          Application.Quit ();
      }
  }

In this case, all I want is to close the application. Applying the script to the OnClick list only gives me MonoScript > string name which I assume is the function name but putting it in, it shows (Missing MonoScript.onClick) and the function doesn't run after building and running. I tested that by just throwing in a Debug message instead of Application.Close();

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

6 Replies

· Add your reply
  • Sort: 
avatar image
15
Best Answer

Answer by digzou · May 27, 2015 at 12:21 PM

If you have created UI button, in your inspector select your button, then

-look for the button script in the inspector,then

-look for "On click"

-Then select your gameobject with "scriptButtonQuit"

-then in the next selection box , select "scriptButtonQuit" -> "onClick()"

check this tutorial : https://unity3d.com/learn/tutorials/modules/beginner/ui/ui-button

alt text


untitled.png (31.8 kB)
Comment
Add comment · Show 8 · 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 Ruarc88 · May 27, 2015 at 01:16 PM 2
Share

This is all I see when trying to do exactly that. Confirmed on the same version of Unity on 2 separate machines:

alt text

untitled.png (31.7 kB)
avatar image digzou · May 27, 2015 at 01:23 PM 0
Share

rename that function to some other name

avatar image Ruarc88 · May 27, 2015 at 02:45 PM 1
Share

Tried rena$$anonymous$$g the function, making a new script, new project, closing and opening after assigning the script to the button, refreshing the script in Assets but still am only seeing $$anonymous$$onoScript > string name as the only option. When I add the main camera ins$$anonymous$$d of my script, I see the right functions for the camera. Adding the script in after that without removing the item from the list still shows $$anonymous$$onoScript > string name.

avatar image digzou · May 27, 2015 at 03:05 PM 8
Share

Got it.

Create an empty gameObject in your scene.

Attach "scriptButtonQuit" script to that gameobject.

Then attach the newly created gameobject in place of the script that you've wrongly attached[below that runtime only thing].

Then you'll be able to find your function.

You cannot directly attach scripts to callbacks. :)

avatar image Ruarc88 · May 27, 2015 at 03:08 PM 1
Share

There we go! $$anonymous$$new I was missing something stupid. Thanks :)

Show more comments
avatar image
9

Answer by ben-rasooli · Mar 02, 2016 at 01:34 AM

In case you wanna assign a function via code you can attach this script (component) to your button gameObject:

 using UnityEngine;
 using UnityEngine.UI; // <-- you need this to access UI (button in this case) functionalities
 
 public class ButtonController : MonoBehaviour {
     Button myButton;
 
     void Awake()
     {
         myButton = GetComponent<Button>(); // <-- you get access to the button component here
 
         myButton.onClick.AddListener( () => {myFunctionForOnClickEvent("stringValue", 4.5f);} );  // <-- you assign a method to the button OnClick event here
         myButton.onClick.AddListener(() => {myAnotherFunctionForOnClickEvent("stringValue", 3);}); // <-- you can assign multiple methods
     }
 
     void myFunctionForOnClickEvent(string argument1, float argument2)
     {
         // your code goes here
         print(argument1 + ", " + argument2.ToString());
     }
 
     void myAnotherFunctionForOnClickEvent(string argument1, int argument2)
     {
         // your code goes here
         print(argument1 + ", " + argument2.ToString());
     }
 }

In this way you can pass in multiple arguments and all sort of other crazy stuff. Just keep in mind though that because Button.onClick.AddListener() accepts zero argument UnityAction, you need to use Lambda Expression if you wanna pass in any argument. example:

() => { methodName(firstArgument, secondArgument, thirdArgument); }

But if you don't wanna pass in any argument, simple hook your method to the onClick listener like so:

myButton.onClick.AddListener( myFunctionForOnClickEvent );

Comment
Add comment · 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
2

Answer by NullTerminated · Aug 15, 2016 at 06:20 PM

So, I ran into the same problem when trying to pass a string to a specific track when the user pressed a button to add track to a Queue. Because of the sheer amount of songs to choose from, there was no way to do this through the inspector. Thus, programmatically doing this was the only good choice.

code starts down here------------------------------------------------------

 void InitializeMusicListContent() 
 {
     for (int i = 0; i < musicData.Count; i++) 
     {
                  // the prefab that is instantiated has a button on one of its children
                 GameObject songPanel = 
                     Instantiate (_songPanelPrefab, this.transform.position, this.transform.rotation, this.transform) as GameObject;
 
                   //Some stuff here that is not important for this......
 
         Button songPanelButton = songPanel.GetComponentInChildren<Button> ();
 
         // must assign it to a variable before supplying it to listener; This IS VERY IMPORTANT
         string x = musicData[i]["TrackPath"];
         songPanelButton.onClick.AddListener(() => {_myAudioPlayer.AddToMusicQueue(x);} );
     }
 }

//code stops here -----------------------------------------

its important to note that I created a variable that held the value that I needed to be passed in. Initially, I was passing in the string directly like so: (DON'T DO THIS, MY FIRST MISTAKE THAT TOOK A LONG TIME TO FIGURE OUT!!!!)

  songPanelButton.onClick.AddListener (
      () => {_myAudioPlayer.AddToMusicQueue(musicData[i]["TrackPath"]);} 
 ); 

  

but this did not work because all buttons actually passed in the same argument. More specifically, the very last track path because that was the last one added to the listener. I don't know why this is the case, but it didn't work until I made a separate variable. Then it worked! So, if you need to pass in parameter that change like in my example, then put the data you need to pass in in a variable first, then in the Lambda.

Hope this helps. Cheers mate.

Comment
Add comment · 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
0

Answer by Deoli · Apr 14, 2016 at 05:41 PM

Maybe you are not usinging the button in a canvas.. see this video:

http://unity3d.com/pt/learn/tutorials/modules/beginner/ui/ui-button

Comment
Add comment · 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
0

Answer by RotemAV · May 08, 2016 at 10:46 AM

myButton.onClick.AddListener(delegate{MyMethod(args);})

Comment
Add comment · 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 Ahapid · May 08, 2017 at 08:48 PM 0
Share

How to access a "$$anonymous$$y $$anonymous$$ethod" in another script?

  • 1
  • 2
  • ›

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

12 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

Related Questions

Button.onClick.AddListener(() => Attack()); isn't running function math correctly 1 Answer

Runtime UI button creation: can't make an "OnClick" where I call a function from another script while sending a parameter. 2 Answers

Calling preset Button OnClick events from another script 3 Answers

button.onClick.AddListener(method); NOT Working 1 Answer

Button OnClick() after Scene restart is Missing (Object) 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