title: Execute function on button press (unity3d/C#)
body: <p>Basically, what I'm trying to do is when pressing Z - it executes function to spin, and X - it executes function to stop spinning. Before, I had UI buttons which worked perfectly fine, now I try doing it by button but nothing happens.</p>
  
  <p>Also, if you can suggest on how to make it start spinning and stop spinning by only pressing "Space" button, that'd be great.</p>
  
  <p>Heres my code so far:</p>
  
  <pre><code>using UnityEngine;
  using System.Collections;
  using UnityEngine.UI;
  
  public class spin : MonoBehaviour
  {
      public float speed = 500f;
      public Button starter;
      public Button stopper;
      bool isSpinning = false;
  
      IEnumerator spinnerCoroutine;
  
      void Start()
      {
          //The spin function
          spinnerCoroutine = spinCOR();
  
          //Button btn = starter.GetComponent&lt;Button&gt;();
          //Button butn = stopper.GetComponent&lt;Button&gt;();
  
          //butn.onClick.AddListener(FidgetSpinnerStop);
          //btn.onClick.AddListener(FidgetSpinnerStart);
  
  
          if (Input.GetKey(KeyCode.Z)) {
  
              FidgetSpinnerStart();
          }
  
          if (Input.GetKey(KeyCode.X)) {
              FidgetSpinnerStop();
          }
      }
  
      IEnumerator spinCOR()
      {
          //Spin forever untill FidgetSpinnerStop is called 
          while (true)
          {
              transform.Rotate(Vector3.up, speed * Time.deltaTime);
              //Wait for the next frame
              yield return null;
          }
      }
  
      void FidgetSpinnerStart()
      {
          //Spin only if it is not spinning
          if (!isSpinning)
          {
              isSpinning = true;
              StartCoroutine(spinnerCoroutine);
          }
      }
  
      void FidgetSpinnerStop()
      {
          //Stop Spinning only if it is already spinning
          if (isSpinning)
          {
              StopCoroutine(spinnerCoroutine);
              isSpinning = false;
          }
      }
  }
  </code></pre>
  
  <p>Thanks.</p>