当前位置:网站首页>Learning record -- superficial understanding of unity decoupling

Learning record -- superficial understanding of unity decoupling

2022-06-23 03:03:00 MrLi001

1、 stay Unity Click on the Button How to display text

① stay Button Mount script on

using UnityEngine;
using UnityEngine.UI;
public class BtnClick:MonoBehaviour
{
    public Text text;
    private void Awake()
    {
        GetComponent<Button>().onClick.AddListener(()=>
        {
            text.text = " This is a text ";
        });
    }
}

stay Button Mount scripts on components , Drag text to Button On component script .

The coupling of this method is too strong , Once the text is missing or not dragged to Button On the script , Will cause the program to be unable to execute .

② Through singleton mode , Mount scripts on text components

text Scripts mounted on

using UnityEngine;
using UnityEngine.UI;
public class ShowText : MonoBehaviour
{
    public static ShowText Instance;
    private void Awake()
    {
        Instance = this;
    }
    public void Show(string str)
    {
        GetComponent<Text>().text = str;
    }
}

Button Scripts mounted on components

using UnityEngine;
using UnityEngine.UI;
public class BtnClick:MonoBehaviour
{
    private void Awake()
    {
        GetComponent<Button>().onClick.AddListener(()=>
        {
            ShowText.Instance.Show(" This is a text ");
        });
    }
}

The problem with the singleton pattern : When text When the singleton mode on is not assigned , There is still a problem with the script on the button , The coupling is still strong .

③ Adopt event monitoring decoupling

text Scripts mounted on

using UnityEngine;
using UnityEngine.UI;
public class ShowText : MonoBehaviour
{
    private void Awake()// Add listening 
    {
        gameObject.SetActive(false);
        EventCenter.AddListener<string>(EventType.ShowText,Show);// entrust ,<> Medium variable type and Show The arguments in the function are related to 
    }
    private void OnDestroy()// Eliminate listening 
    {
        EventCenter.RemoveListener<string>(EventType.ShowText,Show);
    }
    public void Show(string str)
    {
        gameObject.SetActive(true);
        GetComponent<Text>().text = str;
    }
}

Button Scripts mounted on components

using UnityEngine;
using UnityEngine.UI;
public class BtnClick:MonoBehaviour
{
    private void Awake()
    {
        GetComponent<Button>().onClick.AddListener(()=>
        {
            EventCenter.Broadcast(EventType.ShowText," This is a text ");
        });
    }
}

Button Component publishes a broadcast , Whoever listens will be dealt with , If there is no monitor, no error will be reported , It just doesn't execute the corresponding program , The coupling is much smaller .

among EventCenter The categories are as follows :

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

public class EventCenter
{
    private static Dictionary<EventType, Delegate> m_EventTable = new Dictionary<EventType, Delegate>();

    private static void OnListenerAdding(EventType eventType, Delegate callBack)
    {
        if (!m_EventTable.ContainsKey(eventType))
        {
            m_EventTable.Add(eventType, null);
        }
        Delegate d = m_EventTable[eventType];
        if (d != null && d.GetType() != callBack.GetType())
        {
            throw new Exception(string.Format(" Try for events {0} Add different types of delegates , The delegation corresponding to the current event is {1}, The type of delegate to add is {2}", eventType, d.GetType(), callBack.GetType()));
        }
    }
    private static void OnListenerRemoving(EventType eventType, Delegate callBack)
    {
        if (m_EventTable.ContainsKey(eventType))
        {
            Delegate d = m_EventTable[eventType];
            if (d == null)
            {
                throw new Exception(string.Format(" Remove listening errors : event {0} There is no corresponding delegation ", eventType));
            }
            else if (d.GetType() != callBack.GetType())
            {
                throw new Exception(string.Format(" Remove listening errors : Try for events {0} Remove different types of delegates , The current delegate type is {1}, The type of delegate to remove is {2}", eventType, d.GetType(), callBack.GetType()));
            }
        }
        else
        {
            throw new Exception(string.Format(" Remove listening errors : No event code {0}", eventType));
        }
    }
    private static void OnListenerRemoved(EventType eventType)
    {
        if (m_EventTable[eventType] == null)
        {
            m_EventTable.Remove(eventType);
        }
    }
    //no parameters
    public static void AddListener(EventType eventType, CallBack callBack)
    {
        OnListenerAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack)m_EventTable[eventType] + callBack;
    }
    //Single parameters
    public static void AddListener<T>(EventType eventType, CallBack<T> callBack)
    {
        OnListenerAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T>)m_EventTable[eventType] + callBack;
    }
    //two parameters
    public static void AddListener<T, X>(EventType eventType, CallBack<T, X> callBack)
    {
        OnListenerAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X>)m_EventTable[eventType] + callBack;
    }
    //three parameters
    public static void AddListener<T, X, Y>(EventType eventType, CallBack<T, X, Y> callBack)
    {
        OnListenerAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y>)m_EventTable[eventType] + callBack;
    }
    //four parameters
    public static void AddListener<T, X, Y, Z>(EventType eventType, CallBack<T, X, Y, Z> callBack)
    {
        OnListenerAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y, Z>)m_EventTable[eventType] + callBack;
    }
    //five parameters
    public static void AddListener<T, X, Y, Z, W>(EventType eventType, CallBack<T, X, Y, Z, W> callBack)
    {
        OnListenerAdding(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y, Z, W>)m_EventTable[eventType] + callBack;
    }

    //no parameters
    public static void RemoveListener(EventType eventType, CallBack callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }
    //single parameters
    public static void RemoveListener<T>(EventType eventType, CallBack<T> callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T>)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }
    //two parameters
    public static void RemoveListener<T, X>(EventType eventType, CallBack<T, X> callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X>)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }
    //three parameters
    public static void RemoveListener<T, X, Y>(EventType eventType, CallBack<T, X, Y> callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y>)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }
    //four parameters
    public static void RemoveListener<T, X, Y, Z>(EventType eventType, CallBack<T, X, Y, Z> callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y, Z>)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }
    //five parameters
    public static void RemoveListener<T, X, Y, Z, W>(EventType eventType, CallBack<T, X, Y, Z, W> callBack)
    {
        OnListenerRemoving(eventType, callBack);
        m_EventTable[eventType] = (CallBack<T, X, Y, Z, W>)m_EventTable[eventType] - callBack;
        OnListenerRemoved(eventType);
    }


    //no parameters
    public static void Broadcast(EventType eventType)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack callBack = d as CallBack;
            if (callBack != null)
            {
                callBack();
            }
            else
            {
                throw new Exception(string.Format(" Broadcast event error : event {0} The corresponding delegate has different types ", eventType));
            }
        }
    }
    //single parameters
    public static void Broadcast<T>(EventType eventType, T arg)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T> callBack = d as CallBack<T>;
            if (callBack != null)
            {
                callBack(arg);
            }
            else
            {
                throw new Exception(string.Format(" Broadcast event error : event {0} The corresponding delegate has different types ", eventType));
            }
        }
    }
    //two parameters
    public static void Broadcast<T, X>(EventType eventType, T arg1, X arg2)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T, X> callBack = d as CallBack<T, X>;
            if (callBack != null)
            {
                callBack(arg1, arg2);
            }
            else
            {
                throw new Exception(string.Format(" Broadcast event error : event {0} The corresponding delegate has different types ", eventType));
            }
        }
    }
    //three parameters
    public static void Broadcast<T, X, Y>(EventType eventType, T arg1, X arg2, Y arg3)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T, X, Y> callBack = d as CallBack<T, X, Y>;
            if (callBack != null)
            {
                callBack(arg1, arg2, arg3);
            }
            else
            {
                throw new Exception(string.Format(" Broadcast event error : event {0} The corresponding delegate has different types ", eventType));
            }
        }
    }
    //four parameters
    public static void Broadcast<T, X, Y, Z>(EventType eventType, T arg1, X arg2, Y arg3, Z arg4)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T, X, Y, Z> callBack = d as CallBack<T, X, Y, Z>;
            if (callBack != null)
            {
                callBack(arg1, arg2, arg3, arg4);
            }
            else
            {
                throw new Exception(string.Format(" Broadcast event error : event {0} The corresponding delegate has different types ", eventType));
            }
        }
    }
    //five parameters
    public static void Broadcast<T, X, Y, Z, W>(EventType eventType, T arg1, X arg2, Y arg3, Z arg4, W arg5)
    {
        Delegate d;
        if (m_EventTable.TryGetValue(eventType, out d))
        {
            CallBack<T, X, Y, Z, W> callBack = d as CallBack<T, X, Y, Z, W>;
            if (callBack != null)
            {
                callBack(arg1, arg2, arg3, arg4, arg5);
            }
            else
            {
                throw new Exception(string.Format(" Broadcast event error : event {0} The corresponding delegate has different types ", eventType));
            }
        }
    }
}

EventType Class handles listening for different event types

EventType Enumeration of events , You can customize and add listening events :

public enum EventType
{
    ShowText,
}

CallBack Define the delegate class for

public delegate void CallBack();
public delegate void CallBack<T>(T arg);
public delegate void CallBack<T, X>(T arg1, X arg2);
public delegate void CallBack<T, X, Y>(T arg1, X arg2, Y arg3);
public delegate void CallBack<T, X, Y, Z>(T arg1, X arg2, Y arg3, Z arg4);
public delegate void CallBack<T, X, Y, Z, W>(T arg1, X arg2, Y arg3, Z arg4, W arg5);

From the above , Event listening is a good way to handle decoupling .

About the drawbacks of event monitoring : When adding listening, the order of parameter types must be consistent with that of function parameters , When there are many parameters , It's easier to make mistakes

原网站

版权声明
本文为[MrLi001]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/01/202201251633034385.html