前言

Unity UI(UGUI) 是一套基于 GameObject 的 UI 系统,提供了从事件检测到渲染再到用户交互的完整功能。基于 UGUI 系统,我们可以快速构建出一个完整的 UI 界面。虽然 UGUI 使用简单,但是作为一名有追求的游戏开发者,我们不能只停留在使用的层面,更应该深入了解其原理,这样才能更好的根据需求优化甚至扩展 UGUI。

本系列文章将深入 UGUI 底层,从源码角度解析 UGUI 的实现原理,帮助大家建立起对 UGUI 的更深刻理解。

参考资料

UGUI 源码解析

总览

UGUI.png

虽然 UGUI 系统看起来十分庞杂,但是按照功能划分,实际上也就包含了这些功能:

  1. 事件的检测与处理:UGUI 系统要有接收用户输入的能力,并且根据用户的输入来做出相应的回应。如点击按钮后触发事件。

  2. UI 元素的布局与渲染:UI 界面经常涉及到排列的需求,如背包格子、技能栏等。UGUI 系统需要有一套布局系统来实现这些需求。其次,所有的 UI 元素也都要通过渲染系统来显示在屏幕上。

  3. UI 组件库:UGUI 系统提供了一套通用性很强的 UI 组件库,如按钮、滑动条、文本等。基于这些组件基本就可以实现大部分的 UI 界面,当然也可以在此基础上拓展。

文章索引

  1. UIBehaviour

UIBehaviour 是 UGUI 系统中所有组件的基类,该类中定义了一些基本的生命周期函数以及回调函数

点击展开代码
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    /// <summary>
/// Base behaviour that has protected implementations of Unity lifecycle functions.
/// </summary>
public abstract class UIBehaviour : MonoBehaviour
{
protected virtual void Awake()
{}

protected virtual void OnEnable()
{}

protected virtual void Start()
{}

protected virtual void OnDisable()
{}

protected virtual void OnDestroy()
{}

/// <summary>
/// Returns true if the GameObject and the Component are active.
/// </summary>
public virtual bool IsActive()
{
return isActiveAndEnabled;
}

#if UNITY_EDITOR
protected virtual void OnValidate()
{}

protected virtual void Reset()
{}
#endif
/// <summary>
/// This callback is called if an associated RectTransform has its dimensions changed. The call is also made to all child rect transforms, even if the child transform itself doesn't change - as it could have, depending on its anchoring.
/// </summary>
protected virtual void OnRectTransformDimensionsChange()
{}

protected virtual void OnBeforeTransformParentChanged()
{}

protected virtual void OnTransformParentChanged()
{}

protected virtual void OnDidApplyAnimationProperties()
{}

protected virtual void OnCanvasGroupChanged()
{}

/// <summary>
/// Called when the state of the parent Canvas is changed.
/// </summary>
protected virtual void OnCanvasHierarchyChanged()
{}

/// <summary>
/// Returns true if the native representation of the behaviour has been destroyed.
/// </summary>
/// <remarks>
/// When a parent canvas is either enabled, disabled or a nested canvas's OverrideSorting is changed this function is called. You can for example use this to modify objects below a canvas that may depend on a parent canvas - for example, if a canvas is disabled you may want to halt some processing of a UI element.
/// </remarks>
public bool IsDestroyed()
{
// Workaround for Unity native side of the object
// having been destroyed but accessing via interface
// won't call the overloaded ==
return this == null;
}
}
  1. EventSystem
  1. 布局及渲染系统
  1. UI 组件库
  1. 番外篇