【问题标题】:Pass Generic Delegate Argument To UnityEvent将通用委托参数传递给 UnityEvent
【发布时间】:2016-09-03 10:38:27
【问题描述】:

我正在为回调设置一个注册表(我自己的事件处理程序系统)。

客户端代码应该调用Register,并且他们可以添加一个函数来在事件触发时处理事件。因此,例如说 FunctionA 和 FunctionB 都订阅了“GOT_HIT”事件,这两个函数都会被调用。

我知道 UnityEvents 是可行的方法,但我似乎无法真正为它们添加方法。如果我使用参数,我无法正确使用语法。这是我在_battleEvents.AddListener(handler); 上出错的代码,因为:

严重性代码描述项目文件行抑制状态 错误 CS1503 参数 1:无法从“ActionHandler”转换为“UnityEngine.Events.UnityAction>”

这是我对指定委托类型的代码的最佳尝试:

public class ActionEvent:UnityEvent<Dictionary<string, Object>>
{

}

public delegate void ActionHandler(Dictionary<string, Object> props);

public class Dispatcher
{
  static Dispatcher _singleton = new Dispatcher();
  static Dictionary<string, Object> _subscriptions = new Dictionary<string, Object>();

  static ActionEvent _battleEvents = new ActionEvent();


  public static void Register(string actionName, ActionHandler handler)
  {
    switch(actionName)
    {
      case "battle":
        _battleEvents.AddListener(handler);
        break;
      default:
        Debug.Log("Error");
        break;
    }
  }

如果您能告诉我如何正确设置handler 参数,以便添加任何我想传递的函数,那将是理想的。

当我像这样传入匿名函数时,我可以让它工作:

_battleEvents.AddListener((Dictionary<string, Object> props) => { });

但我希望能够从参数中设置它。

可以像这样调用我的实际处理程序:

_battleEvents.AddListener((Dictionary<string, Object> props) => {handler(props); });

但我想跳过那个。

I.E.我想这样做:

  public static void Register(GenericDelegate handler)
  {
      // _battleEvents is UnityEvents object
      _battleEvents.AddListener(handler);
  }

【问题讨论】:

    标签: c# generics unity3d delegates


    【解决方案1】:

    知道了。

    关键是使用UnityAction 类:

      public static void Register(string actionName, UnityAction<Dictionary<string, Object>> handler)
      {
        switch(actionName)
        {
          case "battle":
            _battleEvents.AddListener(handler);
            break;
          default:
            Debug.Log("Error");
            break;
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      • 2020-07-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多