在使用Unity的UGUI時,發現自帶的控件很少,而且功能比較簡單,比如Button在屬性面板中只有一個OnClick事件可以設置。但是我需要有更多功能的Button,比如能在屬性面板中設置OnDown, OnUp, OnEnter, OnExit, OnLongClick這些事件等。我在網上看到有高手做了一些東西來增加相關UI組件的易用性,比如雨松Mono大神的EventTriggerListener類(網址:http://www.xuanyusong.com/archives/3325)。EventTriggerListener類算是比較好用的封裝了,但這需要寫代碼,有時候還是感覺很麻煩。
有麻煩就需要解決,經過這兩天的學習,到處查了資料,后來又找到了ugui的開源代碼(UGUI之前以為沒有開源,造成很多困擾),然后就做了ButtonEx。
我們先來看看效果圖:

可以直接在Hierarchy窗口中右鍵菜單 UI\ButtonEx 添加一個ButtonEx組件。

可以看到多了很多事件設置項。這樣子用起來就方便了。
可以在C#中通過設置 FormerlySerializedAs 來讓事件屬性顯示在 Inspector 面板上。
[Serializable] public class ButtonClickedEvent : UnityEvent {} [FormerlySerializedAs("onClick")] [SerializeField] private ButtonClickedEvent m_OnClick = new ButtonClickedEvent(); [FormerlySerializedAs("onLongClick")] [SerializeField] private ButtonClickedEvent m_OnLongClick = new ButtonClickedEvent(); [FormerlySerializedAs("onDown")] [SerializeField] private ButtonClickedEvent m_OnDown = new ButtonClickedEvent(); [FormerlySerializedAs("onUp")] [SerializeField] private ButtonClickedEvent m_OnUp = new ButtonClickedEvent(); [FormerlySerializedAs("onEnter")] [SerializeField] private ButtonClickedEvent m_OnEnter = new ButtonClickedEvent(); [FormerlySerializedAs("onExit")] [SerializeField] private ButtonClickedEvent m_OnExit = new ButtonClickedEvent();
通過設置 MenuItem 來修改Hierarchy面板的菜單。
[MenuItem("GameObject/UI/ButtonEx")] static void CreateButtonEx(MenuCommand menuCmd) { // 創建游戲對象 float w = 160f; float h = 30f; GameObject btnRoot = UICommon.CreateUIElementRoot("ButtonEx", w, h); // 創建Text對象 UICommon.CreateUIText("Text", "Button", btnRoot); // 添加腳本 btnRoot.AddComponent<CanvasRenderer> (); Image img = btnRoot.AddComponent<Image> (); img.color = Color.white; img.fillCenter = true; img.raycastTarget = true; img.sprite = Common.findRes<Sprite>("UISprite"); if (img.sprite != null) img.type = Image.Type.Sliced; btnRoot.AddComponent<ButtonEx> (); btnRoot.GetComponent<Selectable>().image = img; // 放入到UI Canvas中 UICommon.PlaceUIElementRoot(btnRoot, menuCmd); }
通過設置 AddComponentMenu 實現在主菜單中的 Component 菜單中增加菜單項。
[AddComponentMenu("UI/ButtonEx", 50), RequireComponent(typeof(RectTransform))] public class ButtonEx : Selectable, IPointerClickHandler, ISubmitHandler, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler {
從UGUI的開源代碼中可以看到很多東西的實現, 其中 MenuItem 的添加UI對象的功能, 用到了 MenuOptions, DefaultControls 這兩個類里面的東西, 但是很郁悶的時, 這兩個類里面很多都是私有方法, 我們自定義控件時不能很方便的直接使用, 於是我封裝了 YxdUGUI 這個開源庫, 其中的 UICommon.cs 實現了這兩個類的大部分功能。
有興趣的童鞋可以下載源碼, 有問題歡迎指正, 我會慢慢的完善這個開源庫。
項目開源地址: https://github.com/yangyxd/YxdUGUI
本文為原創內容,轉載請注明出處。
