将参数传递给Unity Action

时间:2017-07-07 18:37:43

标签: c# unity3d unity5

当我启动GameObject时,我会循环遍历所有对话框。每个Dialog都有一个动作。激活任务或更改NPC阶段。

当我点击对话互动中的最后一个按钮时,我传递给下面PopulateConversationList的方法被调用,即"好的"。下面我传递ActiveNpcQuest(questId)方法,并传递questId(从对话框数据中获取),如下所示:

//loop through all dialogs
for (int i = 0; i < dialogData.dialogs.Count; i++) 
    {
        startsQ = dialogData.dialogs[i].dialogStartsQuest;
        questId = dialogData.dialogs[i].dialogBelongToQuestId;

            //if we have a quest, activate it (if already active, nothing happens)
            if (startsQ) 
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, () =>
                {
                    ActivateNPCQuest(questId); //This is the parameter I want to send
                });
            }
            //If this dialog ALWAYS changes the NPC stage, then change stage
            else if (autoChangeStage) 
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, ChangeNPCStage);
            }
        }

我想questId的值实际上并没有保存在ActivateNPCQuest - 方法中。这很有道理。但有什么方法可以做我想要的事情吗?

我的PopulateConversationList声明:

public void PopulateConversationList(List<string> fullConversation, string onLastPagePrompt, string npcName, int stage, UnityAction action)

我的ActiveNpcQuest - 方法:

public void ActivateNPCQuest(int id)
{
    for (int i = 0; i < npcQuests.Count; i++)
    {
        if (npcQuests[i].questId == id && !npcQuests[i].active && !npcQuests[i].objective.isComplete)
        {
            npcQuests[i].active = true;
            npcObject.hasActiveQuest = true;
        }
    }
}

知道要搜索什么的实际问题,不确定Unity Actions是否是Lambda表达式或事件。

1 个答案:

答案 0 :(得分:2)

如果没有完整的代码并知道您的期望,很难理解您的问题,但看起来您因封闭而遇到问题。尝试在循环的每次迭代中将questId分配给一个新变量,并将其传递给ActivateNPCQuest方法,看看是否得到了你想要的结果:

//loop through all dialogs
for (int i = 0; i < dialogData.dialogs.Count; i++) 
    {
        startsQ = dialogData.dialogs[i].dialogStartsQuest;
        var questId = dialogData.dialogs[i].dialogBelongToQuestId; \\<----

            //if we have a quest, activate it (if already active, nothing happens)
            if (startsQ) 
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, () =>
                {
                    ActivateNPCQuest(questId); //This is the parameter I want to send
                });
            }
            //If this dialog ALWAYS changes the NPC stage, then change stage
            else if (autoChangeStage) 
            {
                PopulateConversationList(dialogData.dialogs[i].dialogsInThisStage[j].pages, "Okay", npcObject.npcName, dialogData.dialogs[i].npcStage, ChangeNPCStage);
            }
        }