How do change UI.button onclick variables via script?(JS)
How do change UI.button onclick variables via script?
Answer by Statement · Nov 11, 2015 at 12:06 AM
Use Button.onClick. See also ButtonClickedEvent.
#pragma strict
var button : UI.Button;
function Start()
{
button.onClick.AddListener(CallMePlease);
}
function CallMePlease()
{
print ("Button surely was clicked");
}
To pass a value to the function, you must "curry" or "adapt" the delegate because onClick.AddListener accept a delegate with no arguments. To do this, simply create an anonymous function that adapts the call.
#pragma strict
var button : UI.Button;
function Start()
{
// "Currying" or "adapting" the call to CallMePlease
button.onClick.AddListener( function() { CallMePlease (3); } );
}
function CallMePlease(value : int)
{
print ("Button surely was clicked: " + value);
}
You can also create functions that can help you with adapting the functions in various ways. I'll just give you an example of doing the above, but instead of directly writing the code to adapt the function where its used, you can make a builder function (here called Adapt)
#pragma strict
var button : UI.Button;
function Start()
{
// I chose to go with calling it adapting the function mostly
// because I don't really know if currying is the correct phrase
// to use since we reduce the arguments entirely. What we want
// to do regardless of the vocabulary used is to adapt the function
// CallMePlease(int) into the form CallMePlease().
button.onClick.AddListener(Adapt(CallMePlease, 4));
}
// Accepts a function(int) reference and returns a function() reference.
// When calling the function returned, it will call function(value).
function Adapt(callback : function(int), value : int) : function()
{
return function () { callback (value); };
}
function CallMePlease(value : int)
{
print ("Button surely was clicked: " + value);
}
i need to send variable too.
Like function Start() { button.onClick.AddListener(Call$$anonymous$$ePlease(22)); }
function Call$$anonymous$$ePlease(mapID :int) { print ("map id ="+mapID); }
Updated my answer on how to make a callback that pass an integer.
Basically, you're calling a function that calls another function with the number.
onClick
calls the function() { Call$$anonymous$$ePlease(22); }
, which in turn calls function Call$$anonymous$$ePlease(mapID : int) { /* ... code... */ }
Your answer

Follow this Question
Related Questions
How do you access the text value of the Dropdown UI? 6 Answers
Tips and Tricks Menu Help 1 Answer
How add(create) a new gameobject on scene on mouse button click. 2 Answers
Unable to assign value to Text 0 Answers
Right Click Load Scene help! 1 Answer