代码之家  ›  专栏  ›  技术社区  ›  aybe

合并代理以按顺序而不是同时运行?

  •  0
  • aybe  · 技术社区  · 7 年前

    对于大多数操作来说,一个延迟调用通常就足够了,但有时就不够了。而不是手动链接多个 EditorApplication.delayCall ,我想喝一杯 delay

    但是我很难找到它所需要的代码。

    例子:

    public static void RunDelayed([NotNull] Action action, int delay)
    {
        if (action == null)
            throw new ArgumentNullException(nameof(action));
    
        if (delay <= 0)
            throw new ArgumentOutOfRangeException(nameof(delay));
    
        // 1. expected usage, action will run at next editor update
        EditorApplication.delayCall += () => { action(); };
    
        // 2. wanted usage, be able to delay it by N times, here by 3 times
        // as you can see, to delay by 3 times you have to build a chain of calls
        // which while simple, the number of delays are hard-coded by the amount of times
        // you pasted EditorApplication.delayCall += () =>
    
        EditorApplication.delayCall += () =>
            EditorApplication.delayCall += () =>
                EditorApplication.delayCall += () => { action(); };
    
        // 3. how can the statement above (no. 2) be modeled in a for loop instead ?
        for (var i = 0; i < delay; i++)
        {
            // here I want to do away with manually chaining
            // EditorApplication.delayCall += () => ... statements
            // in turn it allows me to delay by arbitrary N updates
        }
    }
    

    问题:

    参考资料:

    https://docs.unity3d.com/ScriptReference/EditorApplication-delayCall.html

    1 回复  |  直到 7 年前
        1
  •  1
  •   TVOHM    7 年前
    EditorApplication.delayCall += DelayCall.ByNumberOfEditorFrames(4, () => print("Foo"));
    

    实施:

    public static class DelayCall
    {
        public static EditorApplication.CallbackFunction ByNumberOfEditorFrames(int n, Action a)
        {
            EditorApplication.CallbackFunction callback = null;
    
            callback = new EditorApplication.CallbackFunction(() =>
            {
                if (n-- <= 0)
                {
                    a();
                }
                else
                {
                    EditorApplication.delayCall += callback;
                }
            });
    
            return callback;
        }
    }
    

    工作原理:

    返回维护计数器的回调。调用回调时,计数器将递减。如果计数器大于零,回调将自动重新订阅。如果计数器小于或等于零,则调用延迟操作。