How to : smoothly rotate an object over time with a single button click event in Unity3D.
Let us get down to the needy-greedy as quick as possible…
Here’s what your code should look like :
You need a single boolean field “canRotate” at the top, this will allow you to toggle the rotation.
Then you will need to create a simple function that activates this boolean. I named mine “StartRotation”. This is the function that our button will activate later in the tutorial.
After that, you will need to add the IEnumerator Rotate function that does all the work for you.
Button Time!
I’m assuming you’ve added your button that you want to use in your scene under your Canvas object. In my case I want the “PlayButton” to rotate my character/player 180 degrees before the game starts… It should look something like this :
With your button selected in the Hierarchy, look inside your inspector and find the button (script) component.
You should have an area that has On Click () options.
Drag the object(The one that you attached the script above to) that you want to rotate -Mine being the Player object. And do as follows :
Now all you have to do is press Play, click whatever button you’ve setup, and see your work in action! :D
You can modify how much you want your object to rotate by editing the properties that are inside of the Update function after the StartCoroutine method. Example:
You are free to rotate your object on whatever axis you want, by whatever degrees you want, with whatever time you want all inside of this one single function call! :D
I am not claiming that I wrote the IEnumerator Rotate function, I have found it online. With this tutorial I am only providing you the code/tools that I have found publicly with some things modified to aid you in speeding up your workflow process.
— If you would like to give thanks to the creator of the function please check out the link below that shows the post where I found most of this code.
Knowledge and code gathered from :
https://answers.unity.com/questions/1236494/how-to-rotate-fluentlysmoothly.html#answer-1236502