- Home /
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();
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
This is all I see when trying to do exactly that. Confirmed on the same version of Unity on 2 separate machines:
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.
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. :)
There we go! $$anonymous$$new I was missing something stupid. Thanks :)
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 );
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.
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
Answer by RotemAV · May 08, 2016 at 10:46 AM
myButton.onClick.AddListener(delegate{MyMethod(args);})
How to access a "$$anonymous$$y $$anonymous$$ethod" in another script?