How do change UI.button onclick variables via script?
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);
}