Unity进阶-ui框架学习笔记
文章目录
- Unity进阶-ui框架学习笔记
Unity进阶-ui框架学习笔记
笔记来源课程:https://study.163.com/course/courseMain.htm?courseId=1212756805&_trace_c_p_k2_=8c8d7393c43b400d89ae94ab037586fc
- 最上面的管理层(canvas)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class UImanager : MyrSingletonBase<UImanager>
{//下层控制器的字典public Dictionary<string, UIController> UIControllerDic = new Dictionary<string, UIController>();void Start(){}//设置页面激活状态public void SetActive(string controllerName, bool active){transform.Find(controllerName).gameObject.SetActive(active);}//获取页面上的子控件public UIControl GetUIControl(string controllerName, string controlName){//这个字典里是否存在该名称的组件if (UIControllerDic.ContainsKey(controllerName)) {//它下面的字典里是否存在对应组件if (UIControllerDic[controllerName].UIControlDic.ContainsKey(controlName)) {return UIControllerDic[controllerName].UIControlDic[controlName];}}return null;}}
调整下运行顺序,让他快于controller
- panel的控制层
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class UIController : MonoBehaviour
{//下层控制器的字典public Dictionary<string, UIControl> UIControlDic = new Dictionary<string, UIControl>();void Awake() {//添加到UI控制器的字典里UImanager.Instance.UIControllerDic.Add(transform.name, this);//给子控件加上UIcontrol脚本foreach (Transform tran in transform) {if (tran.gameObject.GetComponent<UIControl>() == null) {tran.gameObject.AddComponent<UIControl>();}}}}
- panel下面的组件层
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;public class UIControl : MonoBehaviour
{//父控制器public UIController controller;private void Awake() {//将自身添加到父级控制器上if (transform.parent != null) {controller = transform.GetComponentInParent<UIController>();if (controller != null) {controller.UIControlDic.Add(transform.name, this);}} }///<summary>/// 各个组件对应的函数///</summary>//更改文本public void ChangetText(string str) {if (GetComponent<Text>() != null) {GetComponent<Text>().text = str;}}//更改图片public void ChangeImage(Sprite sprite) {if(GetComponent<Image>() != null) {GetComponent<Image>().sprite = sprite;}}//输入public void AddInputFieldEvent(UnityAction<string> action){InputField control = GetComponent<InputField>();if (control != null) {control.onValueChanged.AddListener(action);}}//Sliderpublic void AddSliderEvent(UnityAction<float> action){Slider control = GetComponent<Slider>();if (control != null) {control.onValueChanged.AddListener(action);}}//Buttonpublic void AddButtonClickEvent(UnityAction action) {Button control = GetComponent<Button>();if (control != null) {control.onClick.AddListener(action);}}
}
-
使用
UImanager.Instance.GetUIControl("score", "scores").ChangetText("分数:" + score);