title: Attach new script to button onclick event in unity3d c#
body: <p>I am creating a new gameobject from c# and trying to execute a script when clecked. here is the code.</p>
  
  <pre><code>    public void createButton(){
              GameObject kGO = new GameObject ();
              kGO.transform.parent = kCanvas.transform;
              kGO.AddComponent&lt;Image&gt;();
              Button btn = kGO.AddComponent&lt;Button&gt;();
              btn.onClick.AddListener(onButtonClick);
      }
  
      public void onButtonClick(){
          Debug.Log ("clicked");
      }
  </code></pre>
  
  <p>but this script is not working, there is not any script attached to the button.
  <a href="https://i.stack.imgur.com/CaBfD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CaBfD.png" alt="enter image description here"></a>.</p>
  
  <p>I have tried these also</p>
  
  <pre><code>btn.onClick.AddListener(() =&gt; {onButtonClick()});
  or
  btn.onClick.AddListener(() =&gt; {onButtonClick();});
  or
  btn.onClick.AddListener(() =&gt; onButtonClick());
  </code></pre>
  
  <p>But nothing is working.</p>