2017-06-18 311 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