Unity3D进阶(四)

UI Button的创建及事件管理 和 UI的动态加载


welcome

UI Button

UI最主要的任务就是展示数据与用户交互,因此可以用来交互的按钮是必不可少的

Button 创建

Button的创建是在Label 或Sprite上添加相应组件实现的

  1. 选中一个Sprite图片右键 Attach -> Box Collider 添加碰撞体,添加的碰撞体会自动适应图片的大小
  2. 继续在图片上右键 Attach -> UI Button 添加按钮组件

UI Button 面板属性

  1. Colors: 可以选择按钮在不同的四种状态下的颜色变化 (normal,hover,pressed,disabled)
  2. Sprites: 与Colors类似可以选择要替换的图片
  3. On Click: 可以拖拽指定的脚本,并选择指定的方法进行响应,但不推荐用这个方法

UI Button 点击事件管理

  1. UI Button 自带的On Click: 将脚本绑定在对应的按钮上,并将此脚本拖拽到On Click中的Notify区域实现事件绑定,操作过于繁琐且不易于统一的管理
  2. 使用事件委托 OnClick方法,为按钮绑定相应的脚本,一个按钮对应一个脚本,同样不利于管理
  3. 为每一个按钮添加 UI Event Listener 组件,在UI Root下创建一个脚本 使用以下方法,就可以在一个脚本中管理所有的按钮事件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
using UnityEngine;
public class clickmanager : MonoBehaviour {
void Awake()
{
//获取按钮对象
GameObject button = GameObject.Find("button");
//将该按钮的 UIEventListener的onClick方法指向到本地类中的自定义方法
UIEventListener.Get(button).onClick = OnButtonclick;
GameObject button2 = GameObject.Find("button2");
UIEventListener.Get(button2).onClick = OnButton2click;
}
//自定义方法,要注意必须带有一个GameObject参数与onClik委托进行匹配
private void OnButtonclick(GameObject button)
{
Debug.Log(1);
}
private void OnButton2click(GameObject button)
{
Debug.Log(2);
}
}


效果展示

UI 动态加载

在UI制作完成后通常将UI Root下的子元素制作为预制体,在场景中动态加载

加载方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using UnityEngine;
public class uimanager : MonoBehaviour {
private GameObject prefab_info;
void Start () {
//将资源文件夹中的UI加载进内存,并保存引用
prefab_info=Resources.Load<GameObject>("info");
//使用NGUITools的AddChild方法为当前UI Root 添加子物体
NGUITools.AddChild(gameObject,prefab_info);
}
}


效果展示

启动之后动态的加载了UI

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. UI Button
    1. 1.1. Button 创建
    2. 1.2. UI Button 面板属性
    3. 1.3. UI Button 点击事件管理
  2. 2. UI 动态加载
    1. 2.1. 加载方法