Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Having trouble instantiating a UnityAction as a field rather than an anonymous delegate.

Discussion in 'Scripting' started by bloomingdedalus, Jun 23, 2015.

  1. bloomingdedalus

    bloomingdedalus

    Joined:
    Aug 13, 2012
    Posts:
    139
    I need to be able to add and remove a listener by script. To do this I need to have the reference to the object I want to remove so an anonymous delegate won't work.

    I simply can't figure out the syntax for the creation and storing in a field of a "UnityAction".

    E.G.

    Code (csharp):
    1.  
    2. private UnityAction MyDel;
    3.  
    4. void Start()
    5. {
    6.       Button MyButton = this.transform.GetComponent<Button>();
    7.      
    8.       MyDel = //  ???????  How do I initialize this?
    9.  
    10.       MyButton.onClick.AddListener(MyDel);
    11. }
    12.  
    13. private void MyUnityActionMethod()
    14. {
    15.       bool DoSomething = true;
    16. }
    17.  
    18.  
     
  2. bloomingdedalus

    bloomingdedalus

    Joined:
    Aug 13, 2012
    Posts:
    139
    Sorry, in case anyone comes across this, you just assign the method directly by name... I feel silly.


    Code (csharp):
    1.  
    2. private UnityAction MyDel;
    3.  
    4. void Start()
    5. {
    6.       Button MyButton = this.transform.GetComponent<Button>();
    7.      
    8.       MyDel = MyUnityActionMethod;
    9.  
    10.       MyButton.onClick.AddListener(MyDel);
    11. }
    12.  
    13. private void MyUnityActionMethod()
    14. {
    15.       bool DoSomething = true;
    16. }
    17.  
    18.  
     
    Mycroft likes this.