Search Unity

Can I assign a static method to the onclick event?

Discussion in 'UGUI & TextMesh Pro' started by SuperCleo, Oct 18, 2014.

  1. SuperCleo

    SuperCleo

    Joined:
    May 30, 2013
    Posts:
    7
    I can't do that in the inspector. I tried to attach a static method via c# like this:
    Code (csharp):
    1. m_NextButton.onClick.AddListener(() => {SomeClass.StaticMehod();});
    No error or warning showed up, but the static method didn't get called when I clicked on the button.
    Did I do it wrong? or could I even do that?
     
  2. User340

    User340

    Joined:
    Feb 28, 2007
    Posts:
    3,001
    Get rid of the double parentheses after .StaticMethod(). This is invoking it.
     
  3. SuperCleo

    SuperCleo

    Joined:
    May 30, 2013
    Posts:
    7
    Thanks for replay. but after deleting those parentheses, unity spits out errors: error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement.
     
  4. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    557
    I'm not sure about the lambda syntax in this case, but this should work:

    Code (csharp):
    1. m_NextButton.onClick.AddListener(delegate{SomeClass.StaticMehod();})
     
  5. SuperCleo

    SuperCleo

    Joined:
    May 30, 2013
    Posts:
    7
    That did not spit any error, but the static method still didn't get called.
    I set a breakpoint before AddListener call, it showed that the field "m_OnClick" of the Button is not set to any instance (Object reference not set to an instance of an object). any idea?
     
  6. mweldon

    mweldon

    Joined:
    Apr 19, 2010
    Posts:
    109
    There doesn't seem to be anything wrong with your syntax as far as I can tell. Try it the old-fashioned way. Make a non-static function, assign it as the listener. Verify that it is being called with a debug log. Then have it call the static function.
     
  7. SuperCleo

    SuperCleo

    Joined:
    May 30, 2013
    Posts:
    7
    It turns out it doesn't work with non-static function either. I must did other thing wrong.
    I set a breakpoint before AddListener call, it showed that the field "m_OnClick" of the Button is not set to any instance (Object reference not set to an instance of an object). any idea?