How To: Animate Your Unity Scenes with Scripts

Hey, it's Kris from Synty, and today we'll be delving into a straightforward rotation script that can add a touch of movement to your game objects.

In this example, I've applied the script to a water wheel in the POLYGON Fantasy Kingdom pack, demonstrating its simplicity and versatility. Let's take a closer look at how to implement this rotation script in your own projects.

Getting Started

Begin by organising your project with a new "Scripts" folder and creating a C# script named "Rotator.cs". Open the script and remove the Start function as we won't be using that in the script. Two parameters are essential: rotateSpeed, a float to control the rotation speed, and rotationDirection, a Vector3 to specify the rotation direction. Both are marked as serialised fields for easy control within the Unity editor.


    [SerializeField]
    float rotationSpeed = 0;

    [SerializeField]
    Vector3 rotationDirection = new Vector3();

Script Implementation

The core of the script lies in the Update() function, utilising transform.Rotate() to animate game objects. The formula involves multiplying rotateSpeed by rotationDirection and then further multiplying it by Time.deltaTime for smooth, frame-rate-independent rotation. Save the script, and let's head back to Unity.


    // Update is called once per frame
    void Update()
    {
        transform.Rotate( rotationSpeed * rotationDirection * Time.deltaTime );
    }

Application in Unity

Drag the "Rotator.cs" script onto the desired game object—like the spinning section of the water wheel. Adjust the parameters as needed. For rotationDirection, observe the initial rotation of your game object; in my example, the X-axis goes into the minus, so I set rotationDirection to -1. Adapt this based on your object's initial rotation.

Applying the Rotator.cs script to the water wheel in Unity

Feel free to reuse this script for other game objects. For instance, I applied the same script to the prop windmill's blades, adjusting the parameters accordingly for a consistent effect.


using UnityEngine;

public class Rotator : MonoBehaviour
{
    [SerializeField]
    float rotationSpeed = 0;

    [SerializeField]
    Vector3 rotationDirection = new Vector3();

    // Update is called once per frame
    void Update()
    {
        transform.Rotate( rotationSpeed * rotationDirection * Time.deltaTime );
    }
}

And there you have it—a practical guide to implementing a basic rotator script. I hope you find this tutorial helpful for bringing subtle movement to your game scenes. Happy coding, and may your game scenes subtly come to life with the Rotator Script!

If you have any specific questions or future tutorial requests, please drop a comment below. For more video tutorials check out our YouTube channel, and to chat with the Synty community of thousands of developers across the globe, jump into our community Discord.

Back to blog