0
\$\begingroup\$

I have a UI Image that I want the user to click and have it rotate 360 degrees once on the z axis. I can get it to rotate through a coroutine but I'm having trouble making it stop once it is started.

public void getInputClick()  // OnClick method for UI object
{
    foreach (Transform child in EventSystem.current.currentSelectedGameObject.GetComponentsInChildren<Transform>())
    {
        if (child.gameObject.name == "Lock")  //Making sure this is an object that should rotate becasue it has a child named "Lock"
        {
            if (rotating == false) //enable coRoutine if not already rotating
            {
                runRotationRoutine = true;
            }
            break;
        }
    }

}

void Update()
{
    if (runRotationRoutine == true)  //Listening for coRoutine execution directive during update.
    {
        StartCoroutine(rotationRoutine());
    }
}

IEnumerator rotationRoutine()
{
    runRotationRoutine = false;  // make sure update doesnt try to run the coroutine more than once!
    rotating = true;  // bool signifying that rotation is currently happening.

    while(rotating == true)
    {
        imageObject.transform.Rotate(rotationVector);
        yield return null;

        //  This works but rotates forever because the coroutine is never terminated.

        //  How do I make this stop after the object has rotated 360 degrees????

        //  Something like (when current rotation == starting rotation --->  set rotation = false
        // But how would I determine this?
    }

}

It needs to be a coroutine because there are a lot of other things executing simultaneously. I feel like it should be pretty simple to just tell it to only rotate around once, what am I missing here?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You just need to keep track of how much rotation you've applied, and break out of the loop when you reach your target:

IEnumerator rotationRoutine()
{
    runRotationRoutine = false;
    rotating = true;
    var total_z_rot = 0.0f;

    while(rotating == true)
    {
        // prevent from over-rotating
        var z_rot = Mathf.Min(360.0f - total_z_rot, rotationVector.z);

        imageObject.transform.Rotate(new Vector3(0.0f, 0.0f, z_rot));
        total_z_rot += z_rot;

        if(total_z_rot >= 360.0f)
        {
            rotating = false;
            break;
        }
        else
        {
            yield return null;
        }
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .