Monkey Original, welcome reprint. Reproduced please specify: reproduced from COCOS2DER-CSDN, thank you!
Original address: http://blog.csdn.net/cocos2der/article/details/42705885
Ugui out so long, also has not been good use, mainly the company project without u3d. Last night with a button, it is still relatively cool.
The main next is to add a button with code. OnClick () Event method (the method added using the properties panel is not said)
Create a 2D UI Panel and add the button you need.
I have added 3 button:btnstart,btnshop,btnleaderboards.
Second, add the script
Using unityengine;using system.collections;using system.collections.generic;using unityengine.events;using Unityengine.ui;public class Mainmenu:monobehaviour {//Use this for Initializationvoid Start () {list<string> Btns Name = new list<string> (); Btnsname.add ("Btnplay"); Btnsname.add ("Btnshop"); Btnsname.add ("btnleaderboards"); foreach (String btnname in Btnsname) {Gameobject btnobj = Gameobject.find (btnname); Button btn = btnobj.getcomponent<button> (); Btn.onClick.AddListener (delegate () {this. OnClick (Btnobj); });} }public void OnClick (gameobject sender) {switch (sender.name) {case ' Btnplay ':D ebug. Log ("Btnplay"); Break;case "Btnshop":D ebug. Log ("Btnshop"); Break;case "Btnleaderboards":D ebug. Log ("Btnleaderboards"); Break;default:debug. Log ("none"); break;}} Update is called once per framevoid update () {}}
OK, test it, you can play.
Ugui adding Button.onclick () events dynamically using code (UNITY3D development 12)