本文链接地址: Unity3D NGUI动态创建按钮
本例仅以熟悉NGUI组件功能为目的,想快捷简便的创建按钮或其它游戏物体请参考 “Unity3D 动态实例化Prefab”
以动态创建服务器列表为例。
- public UIAtlas mAtlas;
- public UIFont mFont;
- public string mSriteName;
- public GameObject Playerlist;
- /// <summary>
- /// 动态加载一个NGUI按钮
- /// </summary>
- /// <param name="name"></param>
- private void CreateServerButton(string key,string name, int index)
- {
- //获得深度(要创建button的Panle的深度)
- int depth = NGUITools.CalculateNextDepth(PanleMe);
- //创建button物体,命名、设tag、摆所在panle的相对位置。
- GameObject go = NGUITools.AddChild(PanleMe);
- go.name = name;
- go.tag = "trendsButton";
- go.transform.localPosition = new Vector3(-180 + (index % 3) * 180, 140, 0);
- //添加button的背景图片UISprite
- UISprite bg = NGUITools.AddWidget<UISprite>(go);
- bg.type = UISprite.Type.Sliced;
- bg.name = "Background";
- bg.depth = depth;
- //背景图片使用的图集
- bg.atlas = mAtlas;
- //图集中使用的精灵名字
- bg.spriteName = mSriteName;
- bg.transform.localScale = new Vector3(150f, 40f, 1f);
- //跳转位置(必要)
- bg.MakePixelPerfect();
- //如果有字体,添加UILabel
- if (mFont != null)
- {
- UILabel lbl = NGUITools.AddWidget<UILabel>(go);
- lbl.font = mFont;
- lbl.text = name;
- lbl.transform.localScale = new Vector3(22f, 22f, 1f);
- lbl.transform.localPosition = new Vector3(0, 0, -1f);
- lbl.color = Color.black;
- lbl.MakePixelPerfect();
- }
- //添加碰撞(有碰撞才能接收鼠标/触摸),大小与Button背景一致
- BoxCollider box = NGUITools.AddWidgetCollider(go);
- box.center = new Vector3(0,0,-1);
- box.size = new Vector3(bg.transform.localScale.x, bg.transform.localScale.y, 0);
- //添加UIButton触发事件的必要组件,并关联之前生成的UISprite
- go.AddComponent<UIButton>().tweenTarget = bg.gameObject;
- //添加动态效果组件(大小、位移、音效)。(可选)
- go.AddComponent<UIButtonScale>();
- go.AddComponent<UIButtonOffset>();
- go.AddComponent<UIButtonSound>();
- /*------ 一下是自己要用到的UIButton功能,可以绑自己需要的组件 ------*/
- //添加一个开启Player list Panel 的按钮事件
- UIButtonTween serverListPanel = go.AddComponent<UIButtonTween>();
- serverListPanel.tweenTarget = PanleNext;
- serverListPanel.playDirection = AnimationOrTween.Direction.Forward;
- serverListPanel.ifDisabledOnPlay = AnimationOrTween.EnableCondition.EnableThenPlay;
- //隐藏自己panel
- UIButtonTween hidemePanel = go.AddComponent<UIButtonTween>();
- hidemePanel.tweenTarget = PanleMe;
- hidemePanel.playDirection = AnimationOrTween.Direction.Reverse;
- hidemePanel.disableWhenFinished = AnimationOrTween.DisableCondition.DisableAfterReverse;
- //添加点击事件,参数是服务器ID(点击获取本服务器ID的下所有角色)
- UIButtonMessage ubm = go.AddComponent<UIButtonMessage>();
- ubm.target = Playerlist;
- //给UIButtonMessage子增加传递‘参数’功能。
- ubm.functionName = "Playerlist";
- ubm.parameterStr = key;
- }
- /// <summary>
- /// 清空动态生成的按钮
- /// </summary>
- void cleantrendsButton()
- {
- GameObject[] tbs = GameObject.FindGameObjectsWithTag("trendsButton");
- for (int i = 0; i < tbs.Length; i++)
- {
- Destroy(tbs[i].gameObject);
- }
- }