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.

2 Answers

2

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

How would you accomplish this in uJS?

–

:( , ( Man of c# ) here

–

@Redwolve it's similar but instead 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);

–

@daneislazy Thank you! I have been looking for it everywhere! No one codes in JS I guess :P

–

For everyone struggling with the problem when using integers instead 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 ()); }

–

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

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-determined argument.

–

Make sure you have "using UnityEngine.UI;" at the top of your script.

–

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.

–

You can also do it with a lamba expression too: BUTTON.onClick.AddListener(() => YourFunction(YourParam));

–