首页 > 解决方案 > 有没有办法列出统一事件?

问题描述

我想做的是我创建了一个 RecipeManager,其中有一个 Recipe 自定义类的列表,允许我选择和创建每个场景的食谱,这也是我要保留事件的地方我创造的。将事件视为食谱中的步骤。我必须制作一个配方系统的想法是会有一系列事件(步骤),当一个步骤完成时它返回一个布尔值,在返回该布尔值时它将进入下一步。我有这一切的想象,但我不知道从哪里开始。也许是这样的:

public List<Events> steps = new List<Events>();

public void IterateThroughSteps()
{
    foreach(var step in steps)
    {
       if(step.isCompleted) // isCompleted is a bool which is true upon the event being triggered
       {
           // Remove step from list
       }
    }
}

摘要:如何制作一个可以按配方模块化的统一事件列表/数组?

希望这个问题符合标准,感谢您的时间。

标签: c#unity3d

解决方案


在您的情况下,仅列出事件列表不会有太大作用。

你的食谱可能是步骤的容器。

public class Recipe : MonoBehaviour
{
    private readonly List<RecipeStep> steps = new List<RecipeStep>(0);
}

现在,您的步骤可以是带有索引号的简单组件(或用于设置订单索引的其他技术)。如果您使用组件方法,请考虑以下事项:

创建自定义统一事件以支持步骤完成:

[System.Serializable]
public sealed class RecipeStepCompletedEvent : UnityEvent<RecipeStep>
{ }

现在,为所有可能的步骤创建基类:

public abstract class RecipeStep : MonoBehaviour
{
    public RecipeStepCompletedEvent StepCompleted;

    public int orderIndex;
}

现在,要收集食谱的所有步骤,只需添加到Recipe.cs

...
private void Awake()
{
    var recipeSteps = GetComponents<RecipeStep>();

    steps.Clear();
    steps.Addrange(recipeSteps);

    // 1. Do sorting by order index or however you like
    // 2. Disable all steps (leave only first step enabled) (steps[X].enabled = false;)
    // 3. Listen to each steps StepCompleted event to be able to progress as step is finished
}

现在让我们创建一个步骤,等待用户按下空格键

public sealed class KeyPressRecipeStep : RecipeStep
{
    public KeyCode desiredKey;

    private void Update()
    {
        if (Input.GetKeyUp(desiredKey))
        {
            StepCompleted.Invoke(this);
        }
    }
}

使用这种方法,您可以根据需要轻松扩展配方和步骤。并且Update()方法不会在被禁用的组件上运行,从而节省了一些宝贵的 CPU 周期。


推荐阅读