Infinite rotation of a game object in Unity 3D C#
In this tutorial, I am going to show you how to rotate a game object continuously for infinite in Unity with the help of C# programming.
In order to rotate a GameObject continuously, we have to use the Rotate method from the Transform component. In the method, we have to provide the direction of the rotation and the rotation speed.
Below is a simple example of rotating an object around its Y-axis or up-axis:
public class InfiniteRotation : MonoBehaviour { public float speedOfRotation = 26f; void Update() { transform.Rotate(Vector3.up, speedOfRotation * Time.deltaTime); } }
In the above program, we first created a float-type variable speedOfRotation
that is going to be our rotation speed. In the Update()
method, we are rotating our GameObject with the provided speed of 26f.
Now let’s see another example where we rotate the object to the both up and down:
public float speedOfRotation = 26f; void Update() { // Rotate object around its Y-axis transform.Rotate(Vector3.up, speedOfRotation * Time.deltaTime); // Rotate object around its X-axis transform.Rotate(Vector3.right, speedOfRotation * Time.deltaTime); }
Just by changing the sign, you can rotate GameObject in the opposite direction:
public float speedOfRotation = 26f; void Update() { // Rotate object around its Y-axis transform.Rotate(Vector3.up, -speedOfRotation * Time.deltaTime); // Rotate object around its X-axis transform.Rotate(Vector3.right, -speedOfRotation * Time.deltaTime); }
As you can see, we have successfully been able to write our C# program for the infinite rotation of a Unity game object.
Leave a Reply