-1
\$\begingroup\$

I am working on a 2D platformer and I am trying to do a character selection menu. I have and button with an event trigger that I use for shooting for the character. My problem is that when I switch to a new character the event trigger that is on the button goes blank and I can no longer shoot. I have tried instantiating the characters and having the SetActive to false. Is there a way to set the event trigger through code or if anybody has any other suggestions I would love to hear them.

Thanks!!

\$\endgroup\$
1
\$\begingroup\$

From what I understood of your issue, you need to dinamically change the Button's onClick property when a character is switched, right? So you need to get access to either that button or its onClick property (which is of type ButtonClickedEvent) and use RemoveAllListeners to remove any method assigned of previous characters, and then use AddListener to add the method of a new character.

AddListener receives an UnityAction which is a delegate of a parameterless void Method's signature, so you need to pass a pointer to a method of that signature. Example:

public class Character : MonoBehaviour
{
    public Button eventButton;

    public void OnCharacterChange()
    {
        eventButton.onClick.RemoveAllListeners();
        eventButton.onClick.AddListener(ButtonEvent);
    }

    void ButtonEvent()
    {
        //...
    }

    void ButtonEventWithParams(string args)
    {
        //...
    }
}

Now, if you would like to add a listener of a method with parameters, you'd need to make a UnityAction's signature method that calls that method with parameter, for you to avoid a creation of that intermediate method, you can either use Lambda Expressions, or do a delegate encapsulation (I think that's the way of calling it, it may be wrong). A quick example:

public class Character : MonoBehaviour
{
    public Button eventButton;

    public void OnCharacterChange()
    {
        eventButton.onClick.RemoveAllListeners();
        //eventButton.onClick.AddListener(ButtonEvent);

        /// With Lambda Expressions:
        eventButton.onClick.AddListener(=>{ ButtonEventWithParams("Hello"); });

        /// With delegate encapsulation:
        eventButton.onClick.AddListener(delegate{ ButtonEventWithParams("Hello"); });
    }

    void ButtonEvent()
    {
        //...
    }

    void ButtonEventWithParams(string arg)
    {
        //...
    }
}

You can check more reference on ButtonClickedEvent's API. Hope it helps.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.