【Unity之UI编程】玩法面板的实现-LMLPHP


👨‍💻个人主页@元宇宙-秩沅

👨‍💻 hallo 欢迎 点赞👍 收藏⭐ 留言📝 加关注✅!

👨‍💻 本文由 秩沅 原创

👨‍💻 收录于专栏UI_Unity专栏

【Unity之UI编程】玩法面板的实现-LMLPHP


UI程序袁



🎶前言


🅰️ ****

【Unity之UI编程】玩法面板的实现-LMLPHP


🎶()开始面板LoginPanel 脚本


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
//-------------------------------------
//—————————————————————————————————————
//___________项目:       ______________
//___________功能: 开始面板
//___________创建者:秩沅_______________
//_____________________________________
//-------------------------------------
public class LoginPanel : BasePanel 
{
    private CanvasGroup PanelGroup;
    // Start is called before the first frame update

    private void Awake()
    {
        PanelGroup = GetComponent<CanvasGroup>();
        if (!PanelGroup)
        {
            PanelGroup = gameObject.AddComponent<CanvasGroup>();
        }

    }

    protected override  void Start()
    {
        base.Start();
        AllEvent();
    }

    /// <summary>
    /// 重写隐藏方法
    /// </summary>
    public override void HideMe()
    {
        Fade(false, PanelGroup);//进行淡出的效果
        base.HideMe();
       
    }
    /// <summary>
    /// 添加控件监听事件
    /// </summary>
    private void AllEvent()
    {
        try
        {
            GetControl<Button>("ButtonS").onClick.AddListener(() =>
            {
                Debug.Log(GetControl<InputField>("InputAC").text);
                //如果账号密码为空
                if (GetControl<InputField>("InputAC").text == "" && GetControl<InputField>("InputAC").text == "")
                {                
                    UIManager.GetInstance().ShowPanel<TipPanel>("TipPanel"); //显示提示面板
                }

            });

        }
        catch
        {
            Debug.Log("没有获取到");
        }


    }
}


🎶()提示面板TipPanel 脚本


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
//-------------------------------------
//—————————————————————————————————————
//___________项目:     
//___________功能:  提示面板
//___________创建者:_______秩沅_____
//_____________________________________
//-------------------------------------

   
public class TipPanel : BasePanel 
{
    private CanvasGroup PanelGroup;
    private UnityAction evnetListen ;
    private void Awake()
    {
        PanelGroup = GetComponent<CanvasGroup>();
        if (!PanelGroup)
        {
            PanelGroup = gameObject.AddComponent<CanvasGroup>();
        }

    }
    protected  override  void Start()
    {
        base.Start();
 
        //添加点击事件
        GetControl<Button>("BtuSure").onClick.AddListener(()=>
        {
            UIManager.GetInstance().RemovePanel("TipPanel");
        });

    }

    /// <summary>
    /// 重写的显示方法
    /// </summary>
    public override void ShowMe()
    {
        Fade(true, PanelGroup);
        base.ShowMe();
    }

    /// <summary>
    /// 重写的隐藏方法
    /// </summary>
    public override void HideMe()
    {
        Fade(false, PanelGroup);
        base.HideMe();
    }

    /// <summary>
    /// 提供给外部改变提示文本内容的方法
    /// </summary>
    /// <param name="component"></param>
    public void ChangComponent(string component)
    {
        GetControl<Text>("ContentText").text = component;
    }
}


优化后的面板基类BasePanel


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// <summary>
/// 面板基类 
/// 帮助我门通过代码快速的找到所有的子控件
/// 方便我们在子类中处理逻辑 
/// 节约找控件的工作量
/// </summary>
public class BasePanel : MonoBehaviour
{
    //通过里式转换原则 来存储所有的控件
    private Dictionary<string, List<UIBehaviour>> controlDic = new Dictionary<string, List<UIBehaviour>>();

	// Use this for initialization
	protected virtual void Start ()
    {
        FindChildrenControl<Button>();
        FindChildrenControl<Image>();
        FindChildrenControl<Text>();
        FindChildrenControl<Toggle>();
        FindChildrenControl<Slider>();
        FindChildrenControl<ScrollRect>();
        FindChildrenControl<InputField>();
    }
	
    /// <summary>
    /// 显示自己
    /// </summary>
    public virtual void ShowMe()
    {
        gameObject.SetActive(true);
    }

    /// <summary>
    /// 隐藏自己
    /// </summary>
    public virtual void HideMe()
    {
        gameObject.SetActive(false);
    }


    /// <summary>
    /// 销毁自己
    /// </summary>
    public virtual void RemoveMe()
    {
        Destroy(gameObject);
    }
    /// <summary>
    /// 得到对应名字的对应控件脚本
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="controlName"></param>
    /// <returns></returns>
    protected T GetControl<T>(string controlName) where T : UIBehaviour
    {
       

        if(controlDic.ContainsKey(controlName))
        {
           
            for( int i = 0; i <controlDic[controlName].Count; ++i )
            {
                if (controlDic[controlName][i] is T)
                {
                    Debug.Log("获取到了" + controlName);
                    return controlDic[controlName][i] as T;
                }
                else
                {
                    Debug.Log("未获取到" );
                }
            }
        }

        return null;
    }

    /// <summary>
    /// 找到面板中子对象的对应控件
    /// </summary>
    /// <typeparam name="T"></typeparam>
    private void FindChildrenControl<T>() where T:UIBehaviour
    {
        
        //把相同类型的空间脚本存储在数组当中
        T[] controls = this.GetComponentsInChildren<T>();      
        for (int i = 0; i < controls.Length; ++i)
        {
            string objName = controls[i].gameObject.name;
          
            if (controlDic.ContainsKey(objName))
                controlDic[objName].Add(controls[i]);
            else
                controlDic.Add(objName, new List<UIBehaviour>() { controls[i] });
            //那如果包含多个相同的空间,并且每个空间执行的逻辑都不一样,那该怎么优化(觉得还是取消这个代码好)
            //除非在这些相同的控件中执行的功能都是一样的
        //如果是按钮控件
            //if(controls[i] is Button)
            //{
            //    (controls[i] as Button).onClick.AddListener(()=>
            //    {
            //        OnClick(objName);
            //    });
            //}
            如果是单选框或者多选框
            //else if(controls[i] is Toggle)
            //{
            //    (controls[i] as Toggle).onValueChanged.AddListener((value) =>
            //    {
            //        OnValueChanged(objName, value);
            //    });
            //}
        }
    }

    /// <summary>
    ///   淡入淡出的效果
    /// </summary>

    public void Fade( bool flag , CanvasGroup Panel)
    {
   
            if (flag)
            {
                Panel.alpha = 0;
                MonoManager.GetInstance().RemoveUpdateListener("fadeOut");
                MonoManager.GetInstance().AddUpdateListener("fadeIn", () =>
                {
                    if(Panel != null )
                    Panel.alpha = Mathf.Lerp(Panel.alpha, 1, Time.deltaTime * 5);
                }
                );

            }
            else
            {
                MonoManager.GetInstance().RemoveUpdateListener("fadeIn");
                MonoManager.GetInstance().AddUpdateListener("fadeOut", () =>
                {
                    if (Panel != null)
                        Panel.alpha = Mathf.Lerp(Panel.alpha, 0, Time.deltaTime * 5);
                }
                );

            }
        }
    
    
}


优化后的Mono管理器


using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEngine;
using UnityEngine.Events;


public class MonoManager : SingleManager<MonoManager>
{
    private MonoController controller;
   
    public MonoManager()
    {
        //保证了MonoController对象的唯一性
        GameObject obj = new GameObject("MonoController");
        controller = obj.AddComponent<MonoController>();
    }

    /// <summary>
    /// 给外部提供的 添加帧更新事件的函数
    /// </summary>
    /// <param name="fun"></param>
    public void AddUpdateListener(string name   ,UnityAction fun)
    {
        controller.AddUpdateListener(name,fun);
    }

    /// <summary>
    /// 提供给外部 用于移除帧更新事件函数
    /// </summary>
    /// <param name="fun"></param>
    public void RemoveUpdateListener(string name)
    {
        controller.RemoveUpdateListener(name);
    }




using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;


public class MonoController : MonoBehaviour {

 
    private Dictionary<string, UnityAction> eventDic = new Dictionary<string, UnityAction>();

    // Use this for initialization
    void Start () {
        DontDestroyOnLoad(this.gameObject);
	}
	
	// Update is called once per frame
	void Update () {
        foreach( UnityAction monoEvent in eventDic.Values )
        {
            if (monoEvent != null)
                monoEvent();
        }
       
    }

    /// <summary>
    /// 给外部提供的 添加帧更新事件的函数
    /// </summary>
    /// <param name="fun"></param>
    public void AddUpdateListener(string name ,UnityAction fun)
    {
        if(eventDic.ContainsKey(name))
        {
            eventDic[name] += fun;
        }
        else
        {
            if(fun != null )
            eventDic.Add(name, fun);
        }
       // updateEvent += fun;
    }

    /// <summary>
    /// 提供给外部 用于移除帧更新事件函数
    /// </summary>
    /// <param name="fun"></param>
    public void RemoveUpdateListener(string name)
    {

        if (eventDic.ContainsKey(name))
        {
            eventDic.Remove(name);
        }
        else
        {
            Debug.Log("未添加过该事件!!");
        }
    }
}


⭐相关文章⭐


软件设计师高频考点大全

unity之c#专题篇—系统强基



你们的点赞👍 收藏⭐ 留言📝 关注✅是我持续创作,输出优质内容的最大动力!

11-12 22:34