2017-06-18 1276 views
1

试图发送一个UnityAction作为一个参数为我的方法之一,比如:传递参数与UnityAction

public void PopulateConversationList(string [] fullConversation, string onLastPagePrompt, string npcName, int stage, UnityAction action) 
{ 
    conversations.Add(new Conversation(fullConversation, onLastPagePrompt, npcName, stage, action)); 
} 

dialogHolder.PopulateConversationList(stage1, "Okay", _name, 1, QuestManager.Instance().ActivateQuest); 

能正常工作,但现在我想下面的行动作为参数传递:

public void ActivateQuest(int questId) 
{ 
    Debug.Log("This is the id: " + questId); 
} 

然而,当我使用的是有一个参数的操作将无法正常工作:

dialogHolder.PopulateConversationList(stage1, "Okay", _name, 1, QuestManager.Instance().ActivateQuest(2)); 

以上给予s错误:Cannot convert from void to UnityAction。 如何将参数传递给UnityAction作为参数?

我叫Action在谈话中是这样的:

dialog.OnAccept(ConvList[i].onLastPagePrompt,() => 
{ 
    ConvList[i].action(); 
    dialog.Hide(); 
}); 

编辑:我最终的解决方案与打算:

enter dialogHolder.PopulateConversationList(stage1, "Okay", _name, 1,() => 
    { 
     QuestManager.Instance().ActivateQuest(0); 
    }); 

这样我可以调用多种方法为好。

+0

你甚至懒得显示'testMethod'函数以及'MyAction'是如何声明的。这些是必需的,以帮助你。 – Programmer

+0

@Programmer对不起,我试图让它更具可读性,我猜想让它变得更糟。我编辑了问: – Majs

回答

1

这里的问题是:

public void PopulateConversationList(string[] fullConversation, string onLastPagePrompt, string npcName, int stage, UnityAction action) 

action参数不接受任何参数,但你传递给它需要一个参数的函数:

public void ActivateQuest(int questId) 
{ 
    Debug.Log("This is the id: " + questId); 
} 

有:

dialogHolder.PopulateConversationList(stage1, "Okay", _name, 1, QuestManager.Instance().ActivateQuest(2)); 

注意2传递给ActivateQuest功能。


将参数传递给UnityEvent并不像预期的那么简单。您必须从UnityEvent中派生出来并提供参数的类型。在这种情况下,你想传递int。您必须创建一个从UnityEvent派生的类,其类型为int

public class IntUnityEvent : UnityEvent<int>{}

IntUnityEvent action变量然后可以在你的函数,而不是UnityAction action传来传的参数。

以下是提供的简化通用解决方案,以便对其他人也有所帮助。只需将您的其他参数添加到PopulateConversationList函数中,您应该很好。它很好评论。

[System.Serializable] 
public class IntUnityEvent : UnityEvent<int> 
{ 
    public int intParam; 
} 

public IntUnityEvent uIntEvent; 

void Start() 
{ 
    //Create the parameter to pass to the function 
    if (uIntEvent == null) 
     uIntEvent = new IntUnityEvent(); 

    //Add the function to call 
    uIntEvent.AddListener(ActivateQuest); 

    //Set the parameter value to use 
    uIntEvent.intParam = 2; 

    //Pass the IntUnityEvent/UnityAction to a function 
    PopulateConversationList(uIntEvent); 
} 

public void PopulateConversationList(IntUnityEvent action) 
{ 
    //Test/Call the function 
    action.Invoke(action.intParam); 
} 

//The function to call 
public void ActivateQuest(int questId) 
{ 
    Debug.Log("This is the id: " + questId); 
} 

注意

如果可能,避免在Unity使用UnityEvent。使用C#Actiondelegate,因为它们更易于使用。而且,它们比Unity的UnityEvent快得多。

+0

谢谢,接受cus它回答我的问题:)我最终找到了我自己的方式,这也让我可以调用我需要的几种方法。 – Majs

+0

太好了。没关系,只要你有它的工作。 – Programmer