Loop function on button press? Unity3d C#

前端 未结 2 974
时光说笑
时光说笑 2021-01-14 12:01

So, I have an object. When I press Spin Button, I want it to spin. When I press Stop button, I want it to stop.

It spins fine when its in void Update, but when its i

2条回答
  •  爱一瞬间的悲伤
    2021-01-14 12:14

    The for loop isn't working as expected because you are not waiting for a frame. Basically, it will do all the spinning in one frame and you won't see the changes until the final spin. Waiting for a frame can the done with yield return null; and that requires a coroutine function.

    This is better done with a coroutine. You can use boolean variable with a coroutine or you can just use StartCoroutine and StopCoroutine. Start coorutine that spins the Object when the start Button is clicked and then stop the coroutine when the stop Button is clicked.

    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

提交回复
热议问题