Creating Unity3D Animations Using C#

If you’ve followed along with my previous articles on Unity3D, you’ll know that we’ve created some objects in a 3D scene and interacted with that scene with a little C#. If you haven’t read the other articles, worry not! There’s nothing in the previous articles you’ll need to know to follow along with this one.

Speaking of this article, let’s look at creating a simple animation, and starting that animation from C#.

Setting Up Our Scene

I’m going to be using Unity3D version 5.4.2f2. To edit scripts, anything that allows you to edit a C# file will be fine.

The first thing we need is a new project in Unity, and, in Figure 1, we can see the settings I’ve selected for this example. You’ll also notice there’s a ‘getting started’ tab on the project setup view; it will lead you some excellent tutorials, examples, and a massive community around Unity to learn from.

Setting up our project
Figure 1: Setting up our project

Next, we need to add a 3D object to our scene, which we’ll animate. One way to do this is from the hierarchy view, which is by default, to the left of the main work area.

Creating a 3D object in our scene
Figure 2: Creating a 3D object in our scene

As we can see in Figure 2, I’ve added a cube to the scene. Next, we need an animation controller, an animation, as well as a C# script. We’ll come to the script last; once we have all elements in our scene, everything else can be done in that script.

In the assets view at the bottom of the scene, let’s create everything else we need by right-clicking the panel then…

  • Create -> Animation controller
  • Create -> Animation
  • Create -> C# Script

Adding the Animation and Animation Controller
Figure 3: Adding the Animation and Animation Controller

Once we have these in our scene, everything should look like what we have in Figure 4…

The elements created
Figure 4: The elements created

Note: The second item from the left, which is represented by the Unity Icon, is just the saved scene.

Before going any further, let’s quickly go over what we are trying to achieve. And, what we are going to do is this. We’ll set up our scene, with the 3D object in the centre—our cube—and when we play the scene, we want that cube to rotate on the left mouse button down event.

Firstly, we’ll create a state, which from code we’ll execute to make the object rotate. To create this state, double-click the animation controller, which is represented with this icon…

The animation control icon
Figure 5: The animation control icon

Once you’ve double-clicked the controller, you’ll have a view that looks like this—minus any states because I’ve gone ahead and created some.

The animation controller with two states pre-created
Figure 6: The animation controller with two states pre-created

The two states I’ve created already are named the ‘Normal’ and ‘MouseDownState’ states. Note that I created the Normal state first and you can create a state by right-clicking the view, then click Create State, and then Empty.

Now, if you look between the two states created, we can see two joining white lines with arrows on them. These are called Tranisations, and to create one, right-click a state and click Make Transition. The state you click is the state the arrow will point away from, and the state you click after starting the creation process is the state the arrow will point to. Therefore, we need to make a transition from each state to the other. Once you have these, there’s a small edit we need to perform on the transition leading from the ‘Normal’ state, to the ‘MouseDownState’. Click the transition and un-check the Has Exit Time option. Figure 7 shows us an example of what you’ll see when you click a transition.

The transition selected and Has Exit Time unchecked
Figure 7: The transition selected and Has Exit Time unchecked

Unchecking the Has Exit option will prevent the ‘Normal’ state from automatically transitioning to the ‘MouseDownState’. Now that we have the basic layout of our controller, let’s create the animation. But, before we move away from the animation controller view, we need to add the animation to the ‘MouseDownState’.

With the state selected, drag the animation we created in our assets to the Motion field shown on the inspector. The animation has this icon…

The Animation icon
Figure 8: The Animation icon

And, the Motion property can be seen here…

The Motion field at the top of the inspect view
Figure 9: The Motion field at the top of the inspect view

Back to our scene view, select the cube in the scene; then drag and drop the Animation Controller onto the cube. Do the same for the script; and then—with the cube still selected—click the add component button at the bottom of the inspector panel. When the components dialogue appears, click Physics, then click Box collider. This box collider will assist us in detecting if the mouse click did indeed hit the 3D object.

If all of the above has gone to plan, you should see these components in the inspector list when you have the cube selected, as shown in Figure 10.

The components added to our 3D object, shown in the inspector panel
Figure 10: The components added to our 3D object, shown in the inspector panel

Now, we’re ready to create a simple rotation animation. From the menu at the top workspace, click Window, and then Animation. The keyboard shortcut for this is Ctrl + 6. If you don’t have your cube selected, go ahead and do so now. Once you do, you should see the animation window become active, with the animation selected. Take a look at Figure 11, then we’ll go over adding a property to animate the rotation.

The animation window, with the property Rotation added to our animation list
Figure 11: The animation window, with the property Rotation added to our animation list

If you click the Add Property button, you’ll see the popup we have above. From there, add the rotation property; then, let’s get to work creating a key frame that will complete the animation. First, expand the property, and move the current time marker to a position of your choice (the red line), and then edit one of the x, y, or z positions like so…

Creating a key frame on our animation time line
Figure 12: Creating a key frame on our animation time line

Once you’ve had a play around with adding key frames to the time line, we can now move on to the C# script, and make our box rotate when we click it.

The C# Script

My script looks something like this…

// Use this for initialization
void Start () {
}

// Update is called once per frame
void Update () {

   // Detect if the left mouse button is down
   if (Input.GetMouseButtonDown(0))
   {
      var ray = Camera.main.ScreenPointToRay
         (Input.mousePosition);
      RaycastHit raycastHit;

      if (Physics.Raycast(ray, out raycastHit, 100))
      {
         // get the collider, which was hit by the ray
         var colliderHit = raycastHit.collider;
         // get the game object the collider is attached to
         var gameObjectHit = colliderHit.gameObject;

         // get the gameObjects animator
         var animator =
            gameObjectHit.GetComponent<Animator>();

         // play the animation
         animator.Play("MouseDownState");
      }
   }
}

And, that’s pretty much it. From the preceding code, we can see it’s possible to get at many of the objects, properties, and anything else we need to build out our game/application.

If you then run the scene, and click the 3D object, we should see some rotation.

The scene running, with visible rotation on the cube
Figure 13: The scene running, with visible rotation on the cube

Conculsion

If you’re just starting out with Unity3D, there’s quite a lot to take in. But, once you’re over the initial information dump, there’s much fun to be had even if you’re just using Unity in your spare time.

If you have any questions on this article, I can be found on Twitter @GLanata.

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read