Ugui adding Button.onclick () events dynamically using code (UNITY3D development 12)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.